/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.policy; import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static android.view.WindowManager.LayoutParams.*; import android.app.ActivityManager; import android.app.SearchManager; import android.os.UserHandle; import android.text.TextUtils; import android.view.ContextThemeWrapper; import android.view.Gravity; import android.view.IRotationWatcher.Stub; import android.view.IWindowManager; import android.view.InputDevice; import android.view.InputEvent; import android.view.InputQueue; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SearchEvent; import android.view.SurfaceHolder.Callback2; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewManager; import android.view.ViewParent; import android.view.ViewRootImpl; import android.view.ViewRootImpl.ActivityConfigCallback; import android.view.Window; import android.view.WindowManager; import com.android.internal.R; import com.android.internal.view.menu.ContextMenuBuilder; import com.android.internal.view.menu.IconMenuPresenter; import com.android.internal.view.menu.ListMenuPresenter; import com.android.internal.view.menu.MenuBuilder; import com.android.internal.view.menu.MenuDialogHelper; import com.android.internal.view.menu.MenuHelper; import com.android.internal.view.menu.MenuPresenter; import com.android.internal.view.menu.MenuView; import com.android.internal.widget.DecorContentParent; import com.android.internal.widget.SwipeDismissLayout; import android.app.ActivityManager; import android.app.KeyguardManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.media.session.MediaController; import android.media.session.MediaSessionLegacyHelper; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Parcel; import android.os.Parcelable; import android.os.RemoteException; import android.os.ServiceManager; import android.provider.Settings; import android.transition.Scene; import android.transition.Transition; import android.transition.TransitionInflater; import android.transition.TransitionManager; import android.transition.TransitionSet; import android.util.AndroidRuntimeException; import android.util.EventLog; import android.util.Log; import android.util.SparseArray; import android.util.TypedValue; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import java.lang.ref.WeakReference; import java.util.ArrayList; /** * Android-specific Window. *
* todo: need to pull the generic functionality out into a base class
* in android.widget.
*
* @hide
*/
public class PhoneWindow extends Window implements MenuBuilder.Callback {
private final static String TAG = "PhoneWindow";
private static final boolean DEBUG = false;
private final static int DEFAULT_BACKGROUND_FADE_DURATION_MS = 300;
private static final int CUSTOM_TITLE_COMPATIBLE_FEATURES = DEFAULT_FEATURES |
(1 << FEATURE_CUSTOM_TITLE) |
(1 << FEATURE_CONTENT_TRANSITIONS) |
(1 << FEATURE_ACTIVITY_TRANSITIONS) |
(1 << FEATURE_ACTION_MODE_OVERLAY);
private static final Transition USE_DEFAULT_TRANSITION = new TransitionSet();
/**
* Simple callback used by the context menu and its submenus. The options
* menu submenus do not use this (their behavior is more complex).
*/
final PhoneWindowMenuCallback mContextMenuCallback = new PhoneWindowMenuCallback(this);
final TypedValue mMinWidthMajor = new TypedValue();
final TypedValue mMinWidthMinor = new TypedValue();
TypedValue mFixedWidthMajor;
TypedValue mFixedWidthMinor;
TypedValue mFixedHeightMajor;
TypedValue mFixedHeightMinor;
// This is the top-level view of the window, containing the window decor.
private DecorView mDecor;
// When we reuse decor views, we need to recreate the content root. This happens when the decor
// view is requested, so we need to force the recreating without introducing an infinite loop.
private boolean mForceDecorInstall = false;
// This is the view in which the window contents are placed. It is either
// mDecor itself, or a child of mDecor where the contents go.
ViewGroup mContentParent;
// Whether the client has explicitly set the content view. If false and mContentParent is not
// null, then the content parent was set due to window preservation.
private boolean mContentParentExplicitlySet = false;
Callback2 mTakeSurfaceCallback;
InputQueue.Callback mTakeInputQueueCallback;
boolean mIsFloating;
private boolean mIsTranslucent;
private LayoutInflater mLayoutInflater;
private TextView mTitleView;
DecorContentParent mDecorContentParent;
private ActionMenuPresenterCallback mActionMenuPresenterCallback;
private PanelMenuPresenterCallback mPanelMenuPresenterCallback;
private TransitionManager mTransitionManager;
private Scene mContentScene;
// The icon resource has been explicitly set elsewhere
// and should not be overwritten with a default.
static final int FLAG_RESOURCE_SET_ICON = 1 << 0;
// The logo resource has been explicitly set elsewhere
// and should not be overwritten with a default.
static final int FLAG_RESOURCE_SET_LOGO = 1 << 1;
// The icon resource is currently configured to use the system fallback
// as no default was previously specified. Anything can override this.
static final int FLAG_RESOURCE_SET_ICON_FALLBACK = 1 << 2;
int mResourcesSetFlags;
int mIconRes;
int mLogoRes;
private DrawableFeatureState[] mDrawables;
private PanelFeatureState[] mPanels;
/**
* The panel that is prepared or opened (the most recent one if there are
* multiple panels). Shortcuts will go to this panel. It gets set in
* {@link #preparePanel} and cleared in {@link #closePanel}.
*/
PanelFeatureState mPreparedPanel;
/**
* The keycode that is currently held down (as a modifier) for chording. If
* this is 0, there is no key held down.
*/
int mPanelChordingKey;
// This stores if the system supports Picture-in-Picture
// to see if KEYCODE_WINDOW should be handled here or not.
private boolean mSupportsPictureInPicture;
private ImageView mLeftIconView;
private ImageView mRightIconView;
private ProgressBar mCircularProgressBar;
private ProgressBar mHorizontalProgressBar;
int mBackgroundResource = 0;
int mBackgroundFallbackResource = 0;
private Drawable mBackgroundDrawable;
private boolean mLoadElevation = true;
private float mElevation;
/** Whether window content should be clipped to the background outline. */
private boolean mClipToOutline;
private int mFrameResource = 0;
private int mTextColor = 0;
int mStatusBarColor = 0;
int mNavigationBarColor = 0;
private boolean mForcedStatusBarColor = false;
private boolean mForcedNavigationBarColor = false;
private CharSequence mTitle = null;
private int mTitleColor = 0;
private boolean mAlwaysReadCloseOnTouchAttr = false;
ContextMenuBuilder mContextMenu;
MenuHelper mContextMenuHelper;
private boolean mClosingActionMenu;
private int mVolumeControlStreamType = AudioManager.USE_DEFAULT_STREAM_TYPE;
private MediaController mMediaController;
private AudioManager mAudioManager;
private KeyguardManager mKeyguardManager;
private int mUiOptions = 0;
private boolean mInvalidatePanelMenuPosted;
private int mInvalidatePanelMenuFeatures;
private final Runnable mInvalidatePanelMenuRunnable = new Runnable() {
@Override public void run() {
for (int i = 0; i <= FEATURE_MAX; i++) {
if ((mInvalidatePanelMenuFeatures & 1 << i) != 0) {
doInvalidatePanelMenu(i);
}
}
mInvalidatePanelMenuPosted = false;
mInvalidatePanelMenuFeatures = 0;
}
};
private Transition mEnterTransition = null;
private Transition mReturnTransition = USE_DEFAULT_TRANSITION;
private Transition mExitTransition = null;
private Transition mReenterTransition = USE_DEFAULT_TRANSITION;
private Transition mSharedElementEnterTransition = null;
private Transition mSharedElementReturnTransition = USE_DEFAULT_TRANSITION;
private Transition mSharedElementExitTransition = null;
private Transition mSharedElementReenterTransition = USE_DEFAULT_TRANSITION;
private Boolean mAllowReturnTransitionOverlap;
private Boolean mAllowEnterTransitionOverlap;
private long mBackgroundFadeDurationMillis = -1;
private Boolean mSharedElementsUseOverlay;
private boolean mIsStartingWindow;
private int mTheme = -1;
private int mDecorCaptionShade = DECOR_CAPTION_SHADE_AUTO;
private boolean mUseDecorContext = false;
/** @see ViewRootImpl#mActivityConfigCallback */
private ActivityConfigCallback mActivityConfigCallback;
static class WindowManagerHolder {
static final IWindowManager sWindowManager = IWindowManager.Stub.asInterface(
ServiceManager.getService("window"));
}
static final RotationWatcher sRotationWatcher = new RotationWatcher();
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
/**
* Constructor for main window of an activity.
*/
public PhoneWindow(Context context, Window preservedWindow,
ActivityConfigCallback activityConfigCallback) {
this(context);
// Only main activity windows use decor context, all the other windows depend on whatever
// context that was given to them.
mUseDecorContext = true;
if (preservedWindow != null) {
mDecor = (DecorView) preservedWindow.getDecorView();
mElevation = preservedWindow.getElevation();
mLoadElevation = false;
mForceDecorInstall = true;
// If we're preserving window, carry over the app token from the preserved
// window, as we'll be skipping the addView in handleResumeActivity(), and
// the token will not be updated as for a new window.
getAttributes().token = preservedWindow.getAttributes().token;
}
// Even though the device doesn't support picture-in-picture mode,
// an user can force using it through developer options.
boolean forceResizable = Settings.Global.getInt(context.getContentResolver(),
DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
mSupportsPictureInPicture = forceResizable || context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_PICTURE_IN_PICTURE);
mActivityConfigCallback = activityConfigCallback;
}
@Override
public final void setContainer(Window container) {
super.setContainer(container);
}
@Override
public boolean requestFeature(int featureId) {
if (mContentParentExplicitlySet) {
throw new AndroidRuntimeException("requestFeature() must be called before adding content");
}
final int features = getFeatures();
final int newFeatures = features | (1 << featureId);
if ((newFeatures & (1 << FEATURE_CUSTOM_TITLE)) != 0 &&
(newFeatures & ~CUSTOM_TITLE_COMPATIBLE_FEATURES) != 0) {
// Another feature is enabled and the user is trying to enable the custom title feature
// or custom title feature is enabled and the user is trying to enable another feature
throw new AndroidRuntimeException(
"You cannot combine custom titles with other title features");
}
if ((features & (1 << FEATURE_NO_TITLE)) != 0 && featureId == FEATURE_ACTION_BAR) {
return false; // Ignore. No title dominates.
}
if ((features & (1 << FEATURE_ACTION_BAR)) != 0 && featureId == FEATURE_NO_TITLE) {
// Remove the action bar feature if we have no title. No title dominates.
removeFeature(FEATURE_ACTION_BAR);
}
if ((features & (1 << FEATURE_ACTION_BAR)) != 0 && featureId == FEATURE_SWIPE_TO_DISMISS) {
throw new AndroidRuntimeException(
"You cannot combine swipe dismissal and the action bar.");
}
if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0 && featureId == FEATURE_ACTION_BAR) {
throw new AndroidRuntimeException(
"You cannot combine swipe dismissal and the action bar.");
}
if (featureId == FEATURE_INDETERMINATE_PROGRESS &&
getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
throw new AndroidRuntimeException("You cannot use indeterminate progress on a watch.");
}
return super.requestFeature(featureId);
}
@Override
public void setUiOptions(int uiOptions) {
mUiOptions = uiOptions;
}
@Override
public void setUiOptions(int uiOptions, int mask) {
mUiOptions = (mUiOptions & ~mask) | (uiOptions & mask);
}
@Override
public TransitionManager getTransitionManager() {
return mTransitionManager;
}
@Override
public void setTransitionManager(TransitionManager tm) {
mTransitionManager = tm;
}
@Override
public Scene getContentScene() {
return mContentScene;
}
@Override
public void setContentView(int layoutResID) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
@Override
public void setContentView(View view) {
setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
view.setLayoutParams(params);
final Scene newScene = new Scene(mContentParent, view);
transitionTo(newScene);
} else {
mContentParent.addView(view, params);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
@Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
if (mContentParent == null) {
installDecor();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
// TODO Augment the scenes/transitions API to support this.
Log.v(TAG, "addContentView does not support content transitions");
}
mContentParent.addView(view, params);
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
@Override
public void clearContentView() {
if (mDecor != null) {
mDecor.clearContentView();
}
}
private void transitionTo(Scene scene) {
if (mContentScene == null) {
scene.enter();
} else {
mTransitionManager.transitionTo(scene);
}
mContentScene = scene;
}
@Override
public View getCurrentFocus() {
return mDecor != null ? mDecor.findFocus() : null;
}
@Override
public void takeSurface(Callback2 callback) {
mTakeSurfaceCallback = callback;
}
public void takeInputQueue(InputQueue.Callback callback) {
mTakeInputQueueCallback = callback;
}
@Override
public boolean isFloating() {
return mIsFloating;
}
public boolean isTranslucent() {
return mIsTranslucent;
}
/**
* @return Whether the window is currently showing the wallpaper.
*/
boolean isShowingWallpaper() {
return (getAttributes().flags & FLAG_SHOW_WALLPAPER) != 0;
}
/**
* Return a LayoutInflater instance that can be used to inflate XML view layout
* resources for use in this Window.
*
* @return LayoutInflater The shared LayoutInflater.
*/
@Override
public LayoutInflater getLayoutInflater() {
return mLayoutInflater;
}
@Override
public void setTitle(CharSequence title) {
setTitle(title, true);
}
public void setTitle(CharSequence title, boolean updateAccessibilityTitle) {
if (mTitleView != null) {
mTitleView.setText(title);
} else if (mDecorContentParent != null) {
mDecorContentParent.setWindowTitle(title);
}
mTitle = title;
if (updateAccessibilityTitle) {
WindowManager.LayoutParams params = getAttributes();
if (!TextUtils.equals(title, params.accessibilityTitle)) {
params.accessibilityTitle = TextUtils.stringOrSpannedString(title);
if (mDecor != null) {
// ViewRootImpl will make sure the change propagates to WindowManagerService
ViewRootImpl vr = mDecor.getViewRootImpl();
if (vr != null) {
vr.onWindowTitleChanged();
}
}
dispatchWindowAttributesChanged(getAttributes());
}
}
}
@Override
@Deprecated
public void setTitleColor(int textColor) {
if (mTitleView != null) {
mTitleView.setTextColor(textColor);
}
mTitleColor = textColor;
}
/**
* Prepares the panel to either be opened or chorded. This creates the Menu
* instance for the panel and populates it via the Activity callbacks.
*
* @param st The panel state to prepare.
* @param event The event that triggered the preparing of the panel.
* @return Whether the panel was prepared. If the panel should not be shown,
* returns false.
*/
public final boolean preparePanel(PanelFeatureState st, KeyEvent event) {
if (isDestroyed()) {
return false;
}
// Already prepared (isPrepared will be reset to false later)
if (st.isPrepared) {
return true;
}
if ((mPreparedPanel != null) && (mPreparedPanel != st)) {
// Another Panel is prepared and possibly open, so close it
closePanel(mPreparedPanel, false);
}
final Callback cb = getCallback();
if (cb != null) {
st.createdPanelView = cb.onCreatePanelView(st.featureId);
}
final boolean isActionBarMenu =
(st.featureId == FEATURE_OPTIONS_PANEL || st.featureId == FEATURE_ACTION_BAR);
if (isActionBarMenu && mDecorContentParent != null) {
// Enforce ordering guarantees around events so that the action bar never
// dispatches menu-related events before the panel is prepared.
mDecorContentParent.setMenuPrepared();
}
if (st.createdPanelView == null) {
// Init the panel state's menu--return false if init failed
if (st.menu == null || st.refreshMenuContent) {
if (st.menu == null) {
if (!initializePanelMenu(st) || (st.menu == null)) {
return false;
}
}
if (isActionBarMenu && mDecorContentParent != null) {
if (mActionMenuPresenterCallback == null) {
mActionMenuPresenterCallback = new ActionMenuPresenterCallback();
}
mDecorContentParent.setMenu(st.menu, mActionMenuPresenterCallback);
}
// Call callback, and return if it doesn't want to display menu.
// Creating the panel menu will involve a lot of manipulation;
// don't dispatch change events to presenters until we're done.
st.menu.stopDispatchingItemsChanged();
if ((cb == null) || !cb.onCreatePanelMenu(st.featureId, st.menu)) {
// Ditch the menu created above
st.setMenu(null);
if (isActionBarMenu && mDecorContentParent != null) {
// Don't show it in the action bar either
mDecorContentParent.setMenu(null, mActionMenuPresenterCallback);
}
return false;
}
st.refreshMenuContent = false;
}
// Callback and return if the callback does not want to show the menu
// Preparing the panel menu can involve a lot of manipulation;
// don't dispatch change events to presenters until we're done.
st.menu.stopDispatchingItemsChanged();
// Restore action view state before we prepare. This gives apps
// an opportunity to override frozen/restored state in onPrepare.
if (st.frozenActionViewState != null) {
st.menu.restoreActionViewStates(st.frozenActionViewState);
st.frozenActionViewState = null;
}
if (!cb.onPreparePanel(st.featureId, st.createdPanelView, st.menu)) {
if (isActionBarMenu && mDecorContentParent != null) {
// The app didn't want to show the menu for now but it still exists.
// Clear it out of the action bar.
mDecorContentParent.setMenu(null, mActionMenuPresenterCallback);
}
st.menu.startDispatchingItemsChanged();
return false;
}
// Set the proper keymap
KeyCharacterMap kmap = KeyCharacterMap.load(
event != null ? event.getDeviceId() : KeyCharacterMap.VIRTUAL_KEYBOARD);
st.qwertyMode = kmap.getKeyboardType() != KeyCharacterMap.NUMERIC;
st.menu.setQwertyMode(st.qwertyMode);
st.menu.startDispatchingItemsChanged();
}
// Set other state
st.isPrepared = true;
st.isHandled = false;
mPreparedPanel = st;
return true;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// Action bars handle their own menu state
if (mDecorContentParent == null) {
PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
if ((st != null) && (st.menu != null)) {
if (st.isOpen) {
// Freeze state
final Bundle state = new Bundle();
if (st.iconMenuPresenter != null) {
st.iconMenuPresenter.saveHierarchyState(state);
}
if (st.listMenuPresenter != null) {
st.listMenuPresenter.saveHierarchyState(state);
}
// Remove the menu views since they need to be recreated
// according to the new configuration
clearMenuViews(st);
// Re-open the same menu
reopenMenu(false);
// Restore state
if (st.iconMenuPresenter != null) {
st.iconMenuPresenter.restoreHierarchyState(state);
}
if (st.listMenuPresenter != null) {
st.listMenuPresenter.restoreHierarchyState(state);
}
} else {
// Clear menu views so on next menu opening, it will use
// the proper layout
clearMenuViews(st);
}
}
}
}
@Override
public void onMultiWindowModeChanged() {
if (mDecor != null) {
mDecor.onConfigurationChanged(getContext().getResources().getConfiguration());
}
}
@Override
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
if (mDecor != null) {
mDecor.updatePictureInPictureOutlineProvider(isInPictureInPictureMode);
}
}
@Override
public void reportActivityRelaunched() {
if (mDecor != null && mDecor.getViewRootImpl() != null) {
mDecor.getViewRootImpl().reportActivityRelaunched();
}
}
private static void clearMenuViews(PanelFeatureState st) {
// This can be called on config changes, so we should make sure
// the views will be reconstructed based on the new orientation, etc.
// Allow the callback to create a new panel view
st.createdPanelView = null;
// Causes the decor view to be recreated
st.refreshDecorView = true;
st.clearMenuPresenters();
}
@Override
public final void openPanel(int featureId, KeyEvent event) {
if (featureId == FEATURE_OPTIONS_PANEL && mDecorContentParent != null &&
mDecorContentParent.canShowOverflowMenu() &&
!ViewConfiguration.get(getContext()).hasPermanentMenuKey()) {
mDecorContentParent.showOverflowMenu();
} else {
openPanel(getPanelState(featureId, true), event);
}
}
private void openPanel(final PanelFeatureState st, KeyEvent event) {
// System.out.println("Open panel: isOpen=" + st.isOpen);
// Already open, return
if (st.isOpen || isDestroyed()) {
return;
}
// Don't open an options panel for honeycomb apps on xlarge devices.
// (The app should be using an action bar for menu items.)
if (st.featureId == FEATURE_OPTIONS_PANEL) {
Context context = getContext();
Configuration config = context.getResources().getConfiguration();
boolean isXLarge = (config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_XLARGE;
boolean isHoneycombApp = context.getApplicationInfo().targetSdkVersion >=
android.os.Build.VERSION_CODES.HONEYCOMB;
if (isXLarge && isHoneycombApp) {
return;
}
}
Callback cb = getCallback();
if ((cb != null) && (!cb.onMenuOpened(st.featureId, st.menu))) {
// Callback doesn't want the menu to open, reset any state
closePanel(st, true);
return;
}
final WindowManager wm = getWindowManager();
if (wm == null) {
return;
}
// Prepare panel (should have been done before, but just in case)
if (!preparePanel(st, event)) {
return;
}
int width = WRAP_CONTENT;
if (st.decorView == null || st.refreshDecorView) {
if (st.decorView == null) {
// Initialize the panel decor, this will populate st.decorView
if (!initializePanelDecor(st) || (st.decorView == null))
return;
} else if (st.refreshDecorView && (st.decorView.getChildCount() > 0)) {
// Decor needs refreshing, so remove its views
st.decorView.removeAllViews();
}
// This will populate st.shownPanelView
if (!initializePanelContent(st) || !st.hasPanelItems()) {
return;
}
ViewGroup.LayoutParams lp = st.shownPanelView.getLayoutParams();
if (lp == null) {
lp = new ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
}
int backgroundResId;
if (lp.width == ViewGroup.LayoutParams.MATCH_PARENT) {
// If the contents is fill parent for the width, set the
// corresponding background
backgroundResId = st.fullBackground;
width = MATCH_PARENT;
} else {
// Otherwise, set the normal panel background
backgroundResId = st.background;
}
st.decorView.setWindowBackground(getContext().getDrawable(
backgroundResId));
ViewParent shownPanelParent = st.shownPanelView.getParent();
if (shownPanelParent != null && shownPanelParent instanceof ViewGroup) {
((ViewGroup) shownPanelParent).removeView(st.shownPanelView);
}
st.decorView.addView(st.shownPanelView, lp);
/*
* Give focus to the view, if it or one of its children does not
* already have it.
*/
if (!st.shownPanelView.hasFocus()) {
st.shownPanelView.requestFocus();
}
} else if (!st.isInListMode()) {
width = MATCH_PARENT;
} else if (st.createdPanelView != null) {
// If we already had a panel view, carry width=MATCH_PARENT through
// as we did above when it was created.
ViewGroup.LayoutParams lp = st.createdPanelView.getLayoutParams();
if (lp != null && lp.width == ViewGroup.LayoutParams.MATCH_PARENT) {
width = MATCH_PARENT;
}
}
st.isHandled = false;
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
width, WRAP_CONTENT,
st.x, st.y, WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
| WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
st.decorView.mDefaultOpacity);
if (st.isCompact) {
lp.gravity = getOptionsPanelGravity();
sRotationWatcher.addWindow(this);
} else {
lp.gravity = st.gravity;
}
lp.windowAnimations = st.windowAnimations;
wm.addView(st.decorView, lp);
st.isOpen = true;
// Log.v(TAG, "Adding main menu to window manager.");
}
@Override
public final void closePanel(int featureId) {
if (featureId == FEATURE_OPTIONS_PANEL && mDecorContentParent != null &&
mDecorContentParent.canShowOverflowMenu() &&
!ViewConfiguration.get(getContext()).hasPermanentMenuKey()) {
mDecorContentParent.hideOverflowMenu();
} else if (featureId == FEATURE_CONTEXT_MENU) {
closeContextMenu();
} else {
closePanel(getPanelState(featureId, true), true);
}
}
/**
* Closes the given panel.
*
* @param st The panel to be closed.
* @param doCallback Whether to notify the callback that the panel was
* closed. If the panel is in the process of re-opening or
* opening another panel (e.g., menu opening a sub menu), the
* callback should not happen and this variable should be false.
* In addition, this method internally will only perform the
* callback if the panel is open.
*/
public final void closePanel(PanelFeatureState st, boolean doCallback) {
// System.out.println("Close panel: isOpen=" + st.isOpen);
if (doCallback && st.featureId == FEATURE_OPTIONS_PANEL &&
mDecorContentParent != null && mDecorContentParent.isOverflowMenuShowing()) {
checkCloseActionMenu(st.menu);
return;
}
final ViewManager wm = getWindowManager();
if ((wm != null) && st.isOpen) {
if (st.decorView != null) {
wm.removeView(st.decorView);
// Log.v(TAG, "Removing main menu from window manager.");
if (st.isCompact) {
sRotationWatcher.removeWindow(this);
}
}
if (doCallback) {
callOnPanelClosed(st.featureId, st, null);
}
}
st.isPrepared = false;
st.isHandled = false;
st.isOpen = false;
// This view is no longer shown, so null it out
st.shownPanelView = null;
if (st.isInExpandedMode) {
// Next time the menu opens, it should not be in expanded mode, so
// force a refresh of the decor
st.refreshDecorView = true;
st.isInExpandedMode = false;
}
if (mPreparedPanel == st) {
mPreparedPanel = null;
mPanelChordingKey = 0;
}
}
void checkCloseActionMenu(Menu menu) {
if (mClosingActionMenu) {
return;
}
mClosingActionMenu = true;
mDecorContentParent.dismissPopups();
Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onPanelClosed(FEATURE_ACTION_BAR, menu);
}
mClosingActionMenu = false;
}
@Override
public final void togglePanel(int featureId, KeyEvent event) {
PanelFeatureState st = getPanelState(featureId, true);
if (st.isOpen) {
closePanel(st, true);
} else {
openPanel(st, event);
}
}
@Override
public void invalidatePanelMenu(int featureId) {
mInvalidatePanelMenuFeatures |= 1 << featureId;
if (!mInvalidatePanelMenuPosted && mDecor != null) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
mInvalidatePanelMenuPosted = true;
}
}
void doPendingInvalidatePanelMenu() {
if (mInvalidatePanelMenuPosted) {
mDecor.removeCallbacks(mInvalidatePanelMenuRunnable);
mInvalidatePanelMenuRunnable.run();
}
}
void doInvalidatePanelMenu(int featureId) {
PanelFeatureState st = getPanelState(featureId, false);
if (st == null) {
return;
}
Bundle savedActionViewStates = null;
if (st.menu != null) {
savedActionViewStates = new Bundle();
st.menu.saveActionViewStates(savedActionViewStates);
if (savedActionViewStates.size() > 0) {
st.frozenActionViewState = savedActionViewStates;
}
// This will be started again when the panel is prepared.
st.menu.stopDispatchingItemsChanged();
st.menu.clear();
}
st.refreshMenuContent = true;
st.refreshDecorView = true;
// Prepare the options panel if we have an action bar
if ((featureId == FEATURE_ACTION_BAR || featureId == FEATURE_OPTIONS_PANEL)
&& mDecorContentParent != null) {
st = getPanelState(Window.FEATURE_OPTIONS_PANEL, false);
if (st != null) {
st.isPrepared = false;
preparePanel(st, null);
}
}
}
/**
* Called when the panel key is pushed down.
* @param featureId The feature ID of the relevant panel (defaults to FEATURE_OPTIONS_PANEL}.
* @param event The key event.
* @return Whether the key was handled.
*/
public final boolean onKeyDownPanel(int featureId, KeyEvent event) {
final int keyCode = event.getKeyCode();
if (event.getRepeatCount() == 0) {
// The panel key was pushed, so set the chording key
mPanelChordingKey = keyCode;
PanelFeatureState st = getPanelState(featureId, false);
if (st != null && !st.isOpen) {
return preparePanel(st, event);
}
}
return false;
}
/**
* Called when the panel key is released.
* @param featureId The feature ID of the relevant panel (defaults to FEATURE_OPTIONS_PANEL}.
* @param event The key event.
*/
public final void onKeyUpPanel(int featureId, KeyEvent event) {
// The panel key was released, so clear the chording key
if (mPanelChordingKey != 0) {
mPanelChordingKey = 0;
final PanelFeatureState st = getPanelState(featureId, false);
if (event.isCanceled() || (mDecor != null && mDecor.mPrimaryActionMode != null) ||
(st == null)) {
return;
}
boolean playSoundEffect = false;
if (featureId == FEATURE_OPTIONS_PANEL && mDecorContentParent != null &&
mDecorContentParent.canShowOverflowMenu() &&
!ViewConfiguration.get(getContext()).hasPermanentMenuKey()) {
if (!mDecorContentParent.isOverflowMenuShowing()) {
if (!isDestroyed() && preparePanel(st, event)) {
playSoundEffect = mDecorContentParent.showOverflowMenu();
}
} else {
playSoundEffect = mDecorContentParent.hideOverflowMenu();
}
} else {
if (st.isOpen || st.isHandled) {
// Play the sound effect if the user closed an open menu (and not if
// they just released a menu shortcut)
playSoundEffect = st.isOpen;
// Close menu
closePanel(st, true);
} else if (st.isPrepared) {
boolean show = true;
if (st.refreshMenuContent) {
// Something may have invalidated the menu since we prepared it.
// Re-prepare it to refresh.
st.isPrepared = false;
show = preparePanel(st, event);
}
if (show) {
// Write 'menu opened' to event log
EventLog.writeEvent(50001, 0);
// Show menu
openPanel(st, event);
playSoundEffect = true;
}
}
}
if (playSoundEffect) {
AudioManager audioManager = (AudioManager) getContext().getSystemService(
Context.AUDIO_SERVICE);
if (audioManager != null) {
audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
} else {
Log.w(TAG, "Couldn't get audio manager");
}
}
}
}
@Override
public final void closeAllPanels() {
final ViewManager wm = getWindowManager();
if (wm == null) {
return;
}
final PanelFeatureState[] panels = mPanels;
final int N = panels != null ? panels.length : 0;
for (int i = 0; i < N; i++) {
final PanelFeatureState panel = panels[i];
if (panel != null) {
closePanel(panel, true);
}
}
closeContextMenu();
}
/**
* Closes the context menu. This notifies the menu logic of the close, along
* with dismissing it from the UI.
*/
private synchronized void closeContextMenu() {
if (mContextMenu != null) {
mContextMenu.close();
dismissContextMenu();
}
}
/**
* Dismisses just the context menu UI. To close the context menu, use
* {@link #closeContextMenu()}.
*/
private synchronized void dismissContextMenu() {
mContextMenu = null;
if (mContextMenuHelper != null) {
mContextMenuHelper.dismiss();
mContextMenuHelper = null;
}
}
@Override
public boolean performPanelShortcut(int featureId, int keyCode, KeyEvent event, int flags) {
return performPanelShortcut(getPanelState(featureId, false), keyCode, event, flags);
}
boolean performPanelShortcut(PanelFeatureState st, int keyCode, KeyEvent event,
int flags) {
if (event.isSystem() || (st == null)) {
return false;
}
boolean handled = false;
// Only try to perform menu shortcuts if preparePanel returned true (possible false
// return value from application not wanting to show the menu).
if ((st.isPrepared || preparePanel(st, event)) && st.menu != null) {
// The menu is prepared now, perform the shortcut on it
handled = st.menu.performShortcut(keyCode, event, flags);
}
if (handled) {
// Mark as handled
st.isHandled = true;
// Only close down the menu if we don't have an action bar keeping it open.
if ((flags & Menu.FLAG_PERFORM_NO_CLOSE) == 0 && mDecorContentParent == null) {
closePanel(st, true);
}
}
return handled;
}
@Override
public boolean performPanelIdentifierAction(int featureId, int id, int flags) {
PanelFeatureState st = getPanelState(featureId, true);
if (!preparePanel(st, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU))) {
return false;
}
if (st.menu == null) {
return false;
}
boolean res = st.menu.performIdentifierAction(id, flags);
// Only close down the menu if we don't have an action bar keeping it open.
if (mDecorContentParent == null) {
closePanel(st, true);
}
return res;
}
public PanelFeatureState findMenuPanel(Menu menu) {
final PanelFeatureState[] panels = mPanels;
final int N = panels != null ? panels.length : 0;
for (int i = 0; i < N; i++) {
final PanelFeatureState panel = panels[i];
if (panel != null && panel.menu == menu) {
return panel;
}
}
return null;
}
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
final PanelFeatureState panel = findMenuPanel(menu.getRootMenu());
if (panel != null) {
return cb.onMenuItemSelected(panel.featureId, item);
}
}
return false;
}
public void onMenuModeChange(MenuBuilder menu) {
reopenMenu(true);
}
private void reopenMenu(boolean toggleMenuMode) {
if (mDecorContentParent != null && mDecorContentParent.canShowOverflowMenu() &&
(!ViewConfiguration.get(getContext()).hasPermanentMenuKey() ||
mDecorContentParent.isOverflowMenuShowPending())) {
final Callback cb = getCallback();
if (!mDecorContentParent.isOverflowMenuShowing() || !toggleMenuMode) {
if (cb != null && !isDestroyed()) {
// If we have a menu invalidation pending, do it now.
if (mInvalidatePanelMenuPosted &&
(mInvalidatePanelMenuFeatures & (1 << FEATURE_OPTIONS_PANEL)) != 0) {
mDecor.removeCallbacks(mInvalidatePanelMenuRunnable);
mInvalidatePanelMenuRunnable.run();
}
final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
// If we don't have a menu or we're waiting for a full content refresh,
// forget it. This is a lingering event that no longer matters.
if (st != null && st.menu != null && !st.refreshMenuContent &&
cb.onPreparePanel(FEATURE_OPTIONS_PANEL, st.createdPanelView, st.menu)) {
cb.onMenuOpened(FEATURE_ACTION_BAR, st.menu);
mDecorContentParent.showOverflowMenu();
}
}
} else {
mDecorContentParent.hideOverflowMenu();
final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
if (st != null && cb != null && !isDestroyed()) {
cb.onPanelClosed(FEATURE_ACTION_BAR, st.menu);
}
}
return;
}
PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
if (st == null) {
return;
}
// Save the future expanded mode state since closePanel will reset it
boolean newExpandedMode = toggleMenuMode ? !st.isInExpandedMode : st.isInExpandedMode;
st.refreshDecorView = true;
closePanel(st, false);
// Set the expanded mode state
st.isInExpandedMode = newExpandedMode;
openPanel(st, null);
}
/**
* Initializes the menu associated with the given panel feature state. You
* must at the very least set PanelFeatureState.menu to the Menu to be
* associated with the given panel state. The default implementation creates
* a new menu for the panel state.
*
* @param st The panel whose menu is being initialized.
* @return Whether the initialization was successful.
*/
protected boolean initializePanelMenu(final PanelFeatureState st) {
Context context = getContext();
// If we have an action bar, initialize the menu with the right theme.
if ((st.featureId == FEATURE_OPTIONS_PANEL || st.featureId == FEATURE_ACTION_BAR) &&
mDecorContentParent != null) {
final TypedValue outValue = new TypedValue();
final Theme baseTheme = context.getTheme();
baseTheme.resolveAttribute(R.attr.actionBarTheme, outValue, true);
Theme widgetTheme = null;
if (outValue.resourceId != 0) {
widgetTheme = context.getResources().newTheme();
widgetTheme.setTo(baseTheme);
widgetTheme.applyStyle(outValue.resourceId, true);
widgetTheme.resolveAttribute(
R.attr.actionBarWidgetTheme, outValue, true);
} else {
baseTheme.resolveAttribute(
R.attr.actionBarWidgetTheme, outValue, true);
}
if (outValue.resourceId != 0) {
if (widgetTheme == null) {
widgetTheme = context.getResources().newTheme();
widgetTheme.setTo(baseTheme);
}
widgetTheme.applyStyle(outValue.resourceId, true);
}
if (widgetTheme != null) {
context = new ContextThemeWrapper(context, 0);
context.getTheme().setTo(widgetTheme);
}
}
final MenuBuilder menu = new MenuBuilder(context);
menu.setCallback(this);
st.setMenu(menu);
return true;
}
/**
* Perform initial setup of a panel. This should at the very least set the
* style information in the PanelFeatureState and must set
* PanelFeatureState.decor to the panel's window decor view.
*
* @param st The panel being initialized.
*/
protected boolean initializePanelDecor(PanelFeatureState st) {
st.decorView = generateDecor(st.featureId);
st.gravity = Gravity.CENTER | Gravity.BOTTOM;
st.setStyle(getContext());
TypedArray a = getContext().obtainStyledAttributes(null,
R.styleable.Window, 0, st.listPresenterTheme);
final float elevation = a.getDimension(R.styleable.Window_windowElevation, 0);
if (elevation != 0) {
st.decorView.setElevation(elevation);
}
a.recycle();
return true;
}
/**
* Determine the gravity value for the options panel. This can
* differ in compact mode.
*
* @return gravity value to use for the panel window
*/
private int getOptionsPanelGravity() {
try {
return WindowManagerHolder.sWindowManager.getPreferredOptionsPanelGravity();
} catch (RemoteException ex) {
Log.e(TAG, "Couldn't getOptionsPanelGravity; using default", ex);
return Gravity.CENTER | Gravity.BOTTOM;
}
}
void onOptionsPanelRotationChanged() {
final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
if (st == null) return;
final WindowManager.LayoutParams lp = st.decorView != null ?
(WindowManager.LayoutParams) st.decorView.getLayoutParams() : null;
if (lp != null) {
lp.gravity = getOptionsPanelGravity();
final ViewManager wm = getWindowManager();
if (wm != null) {
wm.updateViewLayout(st.decorView, lp);
}
}
}
/**
* Initializes the panel associated with the panel feature state. You must
* at the very least set PanelFeatureState.panel to the View implementing
* its contents. The default implementation gets the panel from the menu.
*
* @param st The panel state being initialized.
* @return Whether the initialization was successful.
*/
protected boolean initializePanelContent(PanelFeatureState st) {
if (st.createdPanelView != null) {
st.shownPanelView = st.createdPanelView;
return true;
}
if (st.menu == null) {
return false;
}
if (mPanelMenuPresenterCallback == null) {
mPanelMenuPresenterCallback = new PanelMenuPresenterCallback();
}
MenuView menuView = st.isInListMode()
? st.getListMenuView(getContext(), mPanelMenuPresenterCallback)
: st.getIconMenuView(getContext(), mPanelMenuPresenterCallback);
st.shownPanelView = (View) menuView;
if (st.shownPanelView != null) {
// Use the menu View's default animations if it has any
final int defaultAnimations = menuView.getWindowAnimations();
if (defaultAnimations != 0) {
st.windowAnimations = defaultAnimations;
}
return true;
} else {
return false;
}
}
@Override
public boolean performContextMenuIdentifierAction(int id, int flags) {
return (mContextMenu != null) ? mContextMenu.performIdentifierAction(id, flags) : false;
}
@Override
public final void setElevation(float elevation) {
mElevation = elevation;
final WindowManager.LayoutParams attrs = getAttributes();
if (mDecor != null) {
mDecor.setElevation(elevation);
attrs.setSurfaceInsets(mDecor, true /*manual*/, false /*preservePrevious*/);
}
dispatchWindowAttributesChanged(attrs);
}
@Override
public float getElevation() {
return mElevation;
}
@Override
public final void setClipToOutline(boolean clipToOutline) {
mClipToOutline = clipToOutline;
if (mDecor != null) {
mDecor.setClipToOutline(clipToOutline);
}
}
@Override
public final void setBackgroundDrawable(Drawable drawable) {
if (drawable != mBackgroundDrawable || mBackgroundResource != 0) {
mBackgroundResource = 0;
mBackgroundDrawable = drawable;
if (mDecor != null) {
mDecor.setWindowBackground(drawable);
}
if (mBackgroundFallbackResource != 0) {
mDecor.setBackgroundFallback(drawable != null ? 0 : mBackgroundFallbackResource);
}
}
}
@Override
public final void setFeatureDrawableResource(int featureId, int resId) {
if (resId != 0) {
DrawableFeatureState st = getDrawableState(featureId, true);
if (st.resid != resId) {
st.resid = resId;
st.uri = null;
st.local = getContext().getDrawable(resId);
updateDrawable(featureId, st, false);
}
} else {
setFeatureDrawable(featureId, null);
}
}
@Override
public final void setFeatureDrawableUri(int featureId, Uri uri) {
if (uri != null) {
DrawableFeatureState st = getDrawableState(featureId, true);
if (st.uri == null || !st.uri.equals(uri)) {
st.resid = 0;
st.uri = uri;
st.local = loadImageURI(uri);
updateDrawable(featureId, st, false);
}
} else {
setFeatureDrawable(featureId, null);
}
}
@Override
public final void setFeatureDrawable(int featureId, Drawable drawable) {
DrawableFeatureState st = getDrawableState(featureId, true);
st.resid = 0;
st.uri = null;
if (st.local != drawable) {
st.local = drawable;
updateDrawable(featureId, st, false);
}
}
@Override
public void setFeatureDrawableAlpha(int featureId, int alpha) {
DrawableFeatureState st = getDrawableState(featureId, true);
if (st.alpha != alpha) {
st.alpha = alpha;
updateDrawable(featureId, st, false);
}
}
protected final void setFeatureDefaultDrawable(int featureId, Drawable drawable) {
DrawableFeatureState st = getDrawableState(featureId, true);
if (st.def != drawable) {
st.def = drawable;
updateDrawable(featureId, st, false);
}
}
@Override
public final void setFeatureInt(int featureId, int value) {
// XXX Should do more management (as with drawable features) to
// deal with interactions between multiple window policies.
updateInt(featureId, value, false);
}
/**
* Update the state of a drawable feature. This should be called, for every
* drawable feature supported, as part of onActive(), to make sure that the
* contents of a containing window is properly updated.
*
* @see #onActive
* @param featureId The desired drawable feature to change.
* @param fromActive Always true when called from onActive().
*/
protected final void updateDrawable(int featureId, boolean fromActive) {
final DrawableFeatureState st = getDrawableState(featureId, false);
if (st != null) {
updateDrawable(featureId, st, fromActive);
}
}
/**
* Called when a Drawable feature changes, for the window to update its
* graphics.
*
* @param featureId The feature being changed.
* @param drawable The new Drawable to show, or null if none.
* @param alpha The new alpha blending of the Drawable.
*/
protected void onDrawableChanged(int featureId, Drawable drawable, int alpha) {
ImageView view;
if (featureId == FEATURE_LEFT_ICON) {
view = getLeftIconView();
} else if (featureId == FEATURE_RIGHT_ICON) {
view = getRightIconView();
} else {
return;
}
if (drawable != null) {
drawable.setAlpha(alpha);
view.setImageDrawable(drawable);
view.setVisibility(View.VISIBLE);
} else {
view.setVisibility(View.GONE);
}
}
/**
* Called when an int feature changes, for the window to update its
* graphics.
*
* @param featureId The feature being changed.
* @param value The new integer value.
*/
protected void onIntChanged(int featureId, int value) {
if (featureId == FEATURE_PROGRESS || featureId == FEATURE_INDETERMINATE_PROGRESS) {
updateProgressBars(value);
} else if (featureId == FEATURE_CUSTOM_TITLE) {
FrameLayout titleContainer = findViewById(R.id.title_container);
if (titleContainer != null) {
mLayoutInflater.inflate(value, titleContainer);
}
}
}
/**
* Updates the progress bars that are shown in the title bar.
*
* @param value Can be one of {@link Window#PROGRESS_VISIBILITY_ON},
* {@link Window#PROGRESS_VISIBILITY_OFF},
* {@link Window#PROGRESS_INDETERMINATE_ON},
* {@link Window#PROGRESS_INDETERMINATE_OFF}, or a value
* starting at {@link Window#PROGRESS_START} through
* {@link Window#PROGRESS_END} for setting the default
* progress (if {@link Window#PROGRESS_END} is given,
* the progress bar widgets in the title will be hidden after an
* animation), a value between
* {@link Window#PROGRESS_SECONDARY_START} -
* {@link Window#PROGRESS_SECONDARY_END} for the
* secondary progress (if
* {@link Window#PROGRESS_SECONDARY_END} is given, the
* progress bar widgets will still be shown with the secondary
* progress bar will be completely filled in.)
*/
private void updateProgressBars(int value) {
ProgressBar circularProgressBar = getCircularProgressBar(true);
ProgressBar horizontalProgressBar = getHorizontalProgressBar(true);
final int features = getLocalFeatures();
if (value == PROGRESS_VISIBILITY_ON) {
if ((features & (1 << FEATURE_PROGRESS)) != 0) {
if (horizontalProgressBar != null) {
int level = horizontalProgressBar.getProgress();
int visibility = (horizontalProgressBar.isIndeterminate() || level < 10000) ?
View.VISIBLE : View.INVISIBLE;
horizontalProgressBar.setVisibility(visibility);
} else {
Log.e(TAG, "Horizontal progress bar not located in current window decor");
}
}
if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
if (circularProgressBar != null) {
circularProgressBar.setVisibility(View.VISIBLE);
} else {
Log.e(TAG, "Circular progress bar not located in current window decor");
}
}
} else if (value == PROGRESS_VISIBILITY_OFF) {
if ((features & (1 << FEATURE_PROGRESS)) != 0) {
if (horizontalProgressBar != null) {
horizontalProgressBar.setVisibility(View.GONE);
} else {
Log.e(TAG, "Horizontal progress bar not located in current window decor");
}
}
if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
if (circularProgressBar != null) {
circularProgressBar.setVisibility(View.GONE);
} else {
Log.e(TAG, "Circular progress bar not located in current window decor");
}
}
} else if (value == PROGRESS_INDETERMINATE_ON) {
if (horizontalProgressBar != null) {
horizontalProgressBar.setIndeterminate(true);
} else {
Log.e(TAG, "Horizontal progress bar not located in current window decor");
}
} else if (value == PROGRESS_INDETERMINATE_OFF) {
if (horizontalProgressBar != null) {
horizontalProgressBar.setIndeterminate(false);
} else {
Log.e(TAG, "Horizontal progress bar not located in current window decor");
}
} else if (PROGRESS_START <= value && value <= PROGRESS_END) {
// We want to set the progress value before testing for visibility
// so that when the progress bar becomes visible again, it has the
// correct level.
if (horizontalProgressBar != null) {
horizontalProgressBar.setProgress(value - PROGRESS_START);
} else {
Log.e(TAG, "Horizontal progress bar not located in current window decor");
}
if (value < PROGRESS_END) {
showProgressBars(horizontalProgressBar, circularProgressBar);
} else {
hideProgressBars(horizontalProgressBar, circularProgressBar);
}
} else if (PROGRESS_SECONDARY_START <= value && value <= PROGRESS_SECONDARY_END) {
if (horizontalProgressBar != null) {
horizontalProgressBar.setSecondaryProgress(value - PROGRESS_SECONDARY_START);
} else {
Log.e(TAG, "Horizontal progress bar not located in current window decor");
}
showProgressBars(horizontalProgressBar, circularProgressBar);
}
}
private void showProgressBars(ProgressBar horizontalProgressBar, ProgressBar spinnyProgressBar) {
final int features = getLocalFeatures();
if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0 &&
spinnyProgressBar != null && spinnyProgressBar.getVisibility() == View.INVISIBLE) {
spinnyProgressBar.setVisibility(View.VISIBLE);
}
// Only show the progress bars if the primary progress is not complete
if ((features & (1 << FEATURE_PROGRESS)) != 0 && horizontalProgressBar != null &&
horizontalProgressBar.getProgress() < 10000) {
horizontalProgressBar.setVisibility(View.VISIBLE);
}
}
private void hideProgressBars(ProgressBar horizontalProgressBar, ProgressBar spinnyProgressBar) {
final int features = getLocalFeatures();
Animation anim = AnimationUtils.loadAnimation(getContext(), R.anim.fade_out);
anim.setDuration(1000);
if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0 &&
spinnyProgressBar != null &&
spinnyProgressBar.getVisibility() == View.VISIBLE) {
spinnyProgressBar.startAnimation(anim);
spinnyProgressBar.setVisibility(View.INVISIBLE);
}
if ((features & (1 << FEATURE_PROGRESS)) != 0 && horizontalProgressBar != null &&
horizontalProgressBar.getVisibility() == View.VISIBLE) {
horizontalProgressBar.startAnimation(anim);
horizontalProgressBar.setVisibility(View.INVISIBLE);
}
}
@Override
public void setIcon(int resId) {
mIconRes = resId;
mResourcesSetFlags |= FLAG_RESOURCE_SET_ICON;
mResourcesSetFlags &= ~FLAG_RESOURCE_SET_ICON_FALLBACK;
if (mDecorContentParent != null) {
mDecorContentParent.setIcon(resId);
}
}
@Override
public void setDefaultIcon(int resId) {
if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) != 0) {
return;
}
mIconRes = resId;
if (mDecorContentParent != null && (!mDecorContentParent.hasIcon() ||
(mResourcesSetFlags & FLAG_RESOURCE_SET_ICON_FALLBACK) != 0)) {
if (resId != 0) {
mDecorContentParent.setIcon(resId);
mResourcesSetFlags &= ~FLAG_RESOURCE_SET_ICON_FALLBACK;
} else {
mDecorContentParent.setIcon(
getContext().getPackageManager().getDefaultActivityIcon());
mResourcesSetFlags |= FLAG_RESOURCE_SET_ICON_FALLBACK;
}
}
}
@Override
public void setLogo(int resId) {
mLogoRes = resId;
mResourcesSetFlags |= FLAG_RESOURCE_SET_LOGO;
if (mDecorContentParent != null) {
mDecorContentParent.setLogo(resId);
}
}
@Override
public void setDefaultLogo(int resId) {
if ((mResourcesSetFlags & FLAG_RESOURCE_SET_LOGO) != 0) {
return;
}
mLogoRes = resId;
if (mDecorContentParent != null && !mDecorContentParent.hasLogo()) {
mDecorContentParent.setLogo(resId);
}
}
@Override
public void setLocalFocus(boolean hasFocus, boolean inTouchMode) {
getViewRootImpl().windowFocusChanged(hasFocus, inTouchMode);
}
@Override
public void injectInputEvent(InputEvent event) {
getViewRootImpl().dispatchInputEvent(event);
}
private ViewRootImpl getViewRootImpl() {
if (mDecor != null) {
ViewRootImpl viewRootImpl = mDecor.getViewRootImpl();
if (viewRootImpl != null) {
return viewRootImpl;
}
}
throw new IllegalStateException("view not added");
}
/**
* Request that key events come to this activity. Use this if your activity
* has no views with focus, but the activity still wants a chance to process
* key events.
*/
@Override
public void takeKeyEvents(boolean get) {
mDecor.setFocusable(get);
}
@Override
public boolean superDispatchKeyEvent(KeyEvent event) {
return mDecor.superDispatchKeyEvent(event);
}
@Override
public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
return mDecor.superDispatchKeyShortcutEvent(event);
}
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
@Override
public boolean superDispatchTrackballEvent(MotionEvent event) {
return mDecor.superDispatchTrackballEvent(event);
}
@Override
public boolean superDispatchGenericMotionEvent(MotionEvent event) {
return mDecor.superDispatchGenericMotionEvent(event);
}
/**
* A key was pressed down and not handled by anything else in the window.
*
* @see #onKeyUp
* @see android.view.KeyEvent
*/
protected boolean onKeyDown(int featureId, int keyCode, KeyEvent event) {
/* ****************************************************************************
* HOW TO DECIDE WHERE YOUR KEY HANDLING GOES.
*
* If your key handling must happen before the app gets a crack at the event,
* it goes in PhoneWindowManager.
*
* If your key handling should happen in all windows, and does not depend on
* the state of the current application, other than that the current
* application can override the behavior by handling the event itself, it
* should go in PhoneFallbackEventHandler.
*
* Only if your handling depends on the window, and the fact that it has
* a DecorView, should it go here.
* ****************************************************************************/
final KeyEvent.DispatcherState dispatcher =
mDecor != null ? mDecor.getKeyDispatcherState() : null;
//Log.i(TAG, "Key down: repeat=" + event.getRepeatCount()
// + " flags=0x" + Integer.toHexString(event.getFlags()));
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_MUTE: {
// If we have a session send it the volume command, otherwise
// use the suggested stream.
if (mMediaController != null) {
int direction = 0;
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
direction = AudioManager.ADJUST_RAISE;
break;
case KeyEvent.KEYCODE_VOLUME_DOWN:
direction = AudioManager.ADJUST_LOWER;
break;
case KeyEvent.KEYCODE_VOLUME_MUTE:
direction = AudioManager.ADJUST_TOGGLE_MUTE;
break;
}
mMediaController.adjustVolume(direction, AudioManager.FLAG_SHOW_UI);
} else {
MediaSessionLegacyHelper.getHelper(getContext()).sendVolumeKeyEvent(
event, mVolumeControlStreamType, false);
}
return true;
}
// These are all the recognized media key codes in
// KeyEvent.isMediaKey()
case KeyEvent.KEYCODE_MEDIA_PLAY:
case KeyEvent.KEYCODE_MEDIA_PAUSE:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_MUTE:
case KeyEvent.KEYCODE_HEADSETHOOK:
case KeyEvent.KEYCODE_MEDIA_STOP:
case KeyEvent.KEYCODE_MEDIA_NEXT:
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
case KeyEvent.KEYCODE_MEDIA_REWIND:
case KeyEvent.KEYCODE_MEDIA_RECORD:
case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
if (mMediaController != null) {
if (mMediaController.dispatchMediaButtonEvent(event)) {
return true;
}
}
return false;
}
case KeyEvent.KEYCODE_MENU: {
onKeyDownPanel((featureId < 0) ? FEATURE_OPTIONS_PANEL : featureId, event);
return true;
}
case KeyEvent.KEYCODE_BACK: {
if (event.getRepeatCount() > 0) break;
if (featureId < 0) break;
// Currently don't do anything with long press.
if (dispatcher != null) {
dispatcher.startTracking(event, this);
}
return true;
}
}
return false;
}
private KeyguardManager getKeyguardManager() {
if (mKeyguardManager == null) {
mKeyguardManager = (KeyguardManager) getContext().getSystemService(
Context.KEYGUARD_SERVICE);
}
return mKeyguardManager;
}
AudioManager getAudioManager() {
if (mAudioManager == null) {
mAudioManager = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
}
return mAudioManager;
}
/**
* A key was released and not handled by anything else in the window.
*
* @see #onKeyDown
* @see android.view.KeyEvent
*/
protected boolean onKeyUp(int featureId, int keyCode, KeyEvent event) {
final KeyEvent.DispatcherState dispatcher =
mDecor != null ? mDecor.getKeyDispatcherState() : null;
if (dispatcher != null) {
dispatcher.handleUpEvent(event);
}
//Log.i(TAG, "Key up: repeat=" + event.getRepeatCount()
// + " flags=0x" + Integer.toHexString(event.getFlags()));
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN: {
// If we have a session send it the volume command, otherwise
// use the suggested stream.
if (mMediaController != null) {
final int flags = AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_VIBRATE
| AudioManager.FLAG_FROM_KEY;
mMediaController.adjustVolume(0, flags);
} else {
MediaSessionLegacyHelper.getHelper(getContext()).sendVolumeKeyEvent(
event, mVolumeControlStreamType, false);
}
return true;
}
case KeyEvent.KEYCODE_VOLUME_MUTE: {
// Similar code is in PhoneFallbackEventHandler in case the window
// doesn't have one of these. In this case, we execute it here and
// eat the event instead, because we have mVolumeControlStreamType
// and they don't.
MediaSessionLegacyHelper.getHelper(getContext()).sendVolumeKeyEvent(
event, AudioManager.USE_DEFAULT_STREAM_TYPE, false);
return true;
}
// These are all the recognized media key codes in
// KeyEvent.isMediaKey()
case KeyEvent.KEYCODE_MEDIA_PLAY:
case KeyEvent.KEYCODE_MEDIA_PAUSE:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_MUTE:
case KeyEvent.KEYCODE_HEADSETHOOK:
case KeyEvent.KEYCODE_MEDIA_STOP:
case KeyEvent.KEYCODE_MEDIA_NEXT:
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
case KeyEvent.KEYCODE_MEDIA_REWIND:
case KeyEvent.KEYCODE_MEDIA_RECORD:
case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
if (mMediaController != null) {
if (mMediaController.dispatchMediaButtonEvent(event)) {
return true;
}
}
return false;
}
case KeyEvent.KEYCODE_MENU: {
onKeyUpPanel(featureId < 0 ? FEATURE_OPTIONS_PANEL : featureId,
event);
return true;
}
case KeyEvent.KEYCODE_BACK: {
if (featureId < 0) break;
if (event.isTracking() && !event.isCanceled()) {
if (featureId == FEATURE_OPTIONS_PANEL) {
PanelFeatureState st = getPanelState(featureId, false);
if (st != null && st.isInExpandedMode) {
// If the user is in an expanded menu and hits back, it
// should go back to the icon menu
reopenMenu(true);
return true;
}
}
closePanel(featureId);
return true;
}
break;
}
case KeyEvent.KEYCODE_SEARCH: {
/*
* Do this in onKeyUp since the Search key is also used for
* chording quick launch shortcuts.
*/
if (getKeyguardManager().inKeyguardRestrictedInputMode()) {
break;
}
if (event.isTracking() && !event.isCanceled()) {
launchDefaultSearch(event);
}
return true;
}
case KeyEvent.KEYCODE_WINDOW: {
if (mSupportsPictureInPicture && !event.isCanceled()) {
getWindowControllerCallback().enterPictureInPictureModeIfPossible();
}
return true;
}
}
return false;
}
@Override
protected void onActive() {
}
@Override
public final View getDecorView() {
if (mDecor == null || mForceDecorInstall) {
installDecor();
}
return mDecor;
}
@Override
public final View peekDecorView() {
return mDecor;
}
/** Notify when decor view is attached to window and {@link ViewRootImpl} is available. */
void onViewRootImplSet(ViewRootImpl viewRoot) {
viewRoot.setActivityConfigCallback(mActivityConfigCallback);
}
static private final String FOCUSED_ID_TAG = "android:focusedViewId";
static private final String VIEWS_TAG = "android:views";
static private final String PANELS_TAG = "android:Panels";
static private final String ACTION_BAR_TAG = "android:ActionBar";
/** {@inheritDoc} */
@Override
public Bundle saveHierarchyState() {
Bundle outState = new Bundle();
if (mContentParent == null) {
return outState;
}
SparseArray