/* * * 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.impl; import static android.view.View.MeasureSpec.AT_MOST; import static android.view.View.MeasureSpec.EXACTLY; import static android.view.View.MeasureSpec.getMode; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static android.view.WindowManager.LayoutParams.*; import com.android.internal.view.RootViewSurfaceTaker; import com.android.internal.view.StandaloneActionMode; 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.MenuPresenter; import com.android.internal.view.menu.MenuView; import com.android.internal.widget.ActionBarContainer; import com.android.internal.widget.ActionBarContextView; import com.android.internal.widget.ActionBarOverlayLayout; import com.android.internal.widget.ActionBarView; import android.app.KeyguardManager; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.media.AudioManager; 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.util.AndroidRuntimeException; import android.util.DisplayMetrics; import android.util.EventLog; import android.util.Log; import android.util.SparseArray; import android.util.TypedValue; import android.view.ActionMode; import android.view.ContextThemeWrapper; import android.view.Gravity; import android.view.IRotationWatcher; import android.view.IWindowManager; 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.SurfaceHolder; import android.view.View; import android.view.ViewGroup; import android.view.ViewManager; import android.view.ViewParent; import android.view.ViewStub; import android.view.Window; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.PopupWindow; 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.
*/
public class PhoneWindow extends Window implements MenuBuilder.Callback {
private final static String TAG = "PhoneWindow";
private final static boolean SWEEP_OPEN_MENU = false;
/**
* Simple callback used by the context menu and its submenus. The options
* menu submenus do not use this (their behavior is more complex).
*/
final DialogMenuCallback mContextMenuCallback = new DialogMenuCallback(FEATURE_CONTEXT_MENU);
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;
// 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.
private ViewGroup mContentParent;
SurfaceHolder.Callback2 mTakeSurfaceCallback;
InputQueue.Callback mTakeInputQueueCallback;
private boolean mIsFloating;
private LayoutInflater mLayoutInflater;
private TextView mTitleView;
private ActionBarView mActionBar;
private ActionMenuPresenterCallback mActionMenuPresenterCallback;
private PanelMenuPresenterCallback mPanelMenuPresenterCallback;
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}.
*/
private PanelFeatureState mPreparedPanel;
/**
* The keycode that is currently held down (as a modifier) for chording. If
* this is 0, there is no key held down.
*/
private int mPanelChordingKey;
private ImageView mLeftIconView;
private ImageView mRightIconView;
private ProgressBar mCircularProgressBar;
private ProgressBar mHorizontalProgressBar;
private int mBackgroundResource = 0;
private Drawable mBackgroundDrawable;
private int mFrameResource = 0;
private int mTextColor = 0;
private CharSequence mTitle = null;
private int mTitleColor = 0;
private boolean mAlwaysReadCloseOnTouchAttr = false;
private ContextMenuBuilder mContextMenu;
private MenuDialogHelper mContextMenuHelper;
private boolean mClosingActionMenu;
private int mVolumeControlStreamType = AudioManager.USE_DEFAULT_STREAM_TYPE;
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;
}
};
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);
}
@Override
public final void setContainer(Window container) {
super.setContainer(container);
}
@Override
public boolean requestFeature(int featureId) {
if (mContentParent != null) {
throw new AndroidRuntimeException("requestFeature() must be called before adding content");
}
final int features = getFeatures();
if ((features != DEFAULT_FEATURES) && (featureId == FEATURE_CUSTOM_TITLE)) {
/* Another feature is enabled and the user is trying to enable the custom title feature */
throw new AndroidRuntimeException("You cannot combine custom titles with other title features");
}
if (((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) &&
(featureId != FEATURE_CUSTOM_TITLE) && (featureId != FEATURE_ACTION_MODE_OVERLAY)) {
/* 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);
}
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 void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
mLayoutInflater.inflate(layoutResID, mContentParent);
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
@Override
public void setContentView(View view) {
setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
mContentParent.addView(view, params);
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
@Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
if (mContentParent == null) {
installDecor();
}
mContentParent.addView(view, params);
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
@Override
public View getCurrentFocus() {
return mDecor != null ? mDecor.findFocus() : null;
}
@Override
public void takeSurface(SurfaceHolder.Callback2 callback) {
mTakeSurfaceCallback = callback;
}
public void takeInputQueue(InputQueue.Callback callback) {
mTakeInputQueueCallback = callback;
}
@Override
public boolean isFloating() {
return mIsFloating;
}
/**
* 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) {
if (mTitleView != null) {
mTitleView.setText(title);
} else if (mActionBar != null) {
mActionBar.setWindowTitle(title);
}
mTitle = title;
}
@Override
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 && mActionBar != null) {
// Enforce ordering guarantees around events so that the action bar never
// dispatches menu-related events before the panel is prepared.
mActionBar.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 && mActionBar != null) {
if (mActionMenuPresenterCallback == null) {
mActionMenuPresenterCallback = new ActionMenuPresenterCallback();
}
mActionBar.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 && mActionBar != null) {
// Don't show it in the action bar either
mActionBar.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 && mActionBar != null) {
// The app didn't want to show the menu for now but it still exists.
// Clear it out of the action bar.
mActionBar.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 (mActionBar == 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);
}
}
}
}
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 && mActionBar != null &&
mActionBar.isOverflowReserved()) {
if (mActionBar.getVisibility() == View.VISIBLE) {
mActionBar.showOverflowMenu();
}
} else {
openPanel(getPanelState(featureId, true), event);
}
}
private void openPanel(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().getResources().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.isOpen = true;
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);
// Log.v(TAG, "Adding main menu to window manager.");
}
@Override
public final void closePanel(int featureId) {
if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null &&
mActionBar.isOverflowReserved()) {
mActionBar.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 &&
mActionBar != null && mActionBar.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;
mActionBar.dismissPopupMenus();
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 doInvalidatePanelMenu(int featureId) {
PanelFeatureState st = getPanelState(featureId, true);
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)
&& mActionBar != 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, true);
if (!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;
if (event.isCanceled() || (mDecor != null && mDecor.mActionMode != null)) {
return;
}
boolean playSoundEffect = false;
final PanelFeatureState st = getPanelState(featureId, true);
if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null &&
mActionBar.isOverflowReserved()) {
if (mActionBar.getVisibility() == View.VISIBLE) {
if (!mActionBar.isOverflowMenuShowing()) {
if (!isDestroyed() && preparePanel(st, event)) {
playSoundEffect = mActionBar.showOverflowMenu();
}
} else {
playSoundEffect = mActionBar.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, true), keyCode, event, flags);
}
private 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 && mActionBar == 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 (mActionBar == 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 (mActionBar != null && mActionBar.isOverflowReserved()) {
final Callback cb = getCallback();
if (!mActionBar.isOverflowMenuShowing() || !toggleMenuMode) {
if (cb != null && !isDestroyed() && mActionBar.getVisibility() == View.VISIBLE) {
// 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, true);
// 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.menu != null && !st.refreshMenuContent &&
cb.onPreparePanel(FEATURE_OPTIONS_PANEL, st.createdPanelView, st.menu)) {
cb.onMenuOpened(FEATURE_ACTION_BAR, st.menu);
mActionBar.showOverflowMenu();
}
}
} else {
mActionBar.hideOverflowMenu();
if (cb != null && !isDestroyed()) {
final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
cb.onPanelClosed(FEATURE_ACTION_BAR, st.menu);
}
}
return;
}
PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
// 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 a context themed for it.
if ((st.featureId == FEATURE_OPTIONS_PANEL || st.featureId == FEATURE_ACTION_BAR) &&
mActionBar != null) {
TypedValue outValue = new TypedValue();
Resources.Theme currentTheme = context.getTheme();
currentTheme.resolveAttribute(com.android.internal.R.attr.actionBarWidgetTheme,
outValue, true);
final int targetThemeRes = outValue.resourceId;
if (targetThemeRes != 0 && context.getThemeResId() != targetThemeRes) {
context = new ContextThemeWrapper(context, targetThemeRes);
}
}
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 = new DecorView(getContext(), st.featureId);
st.gravity = Gravity.CENTER | Gravity.BOTTOM;
st.setStyle(getContext());
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 setBackgroundDrawable(Drawable drawable) {
if (drawable != mBackgroundDrawable || mBackgroundResource != 0) {
mBackgroundResource = 0;
mBackgroundDrawable = drawable;
if (mDecor != null) {
mDecor.setWindowBackground(drawable);
}
}
}
@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().getResources().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 = (FrameLayout) findViewById(com.android.internal.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) {
int level = horizontalProgressBar.getProgress();
int visibility = (horizontalProgressBar.isIndeterminate() || level < 10000) ?
View.VISIBLE : View.INVISIBLE;
horizontalProgressBar.setVisibility(visibility);
}
if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
circularProgressBar.setVisibility(View.VISIBLE);
}
} else if (value == PROGRESS_VISIBILITY_OFF) {
if ((features & (1 << FEATURE_PROGRESS)) != 0) {
horizontalProgressBar.setVisibility(View.GONE);
}
if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
circularProgressBar.setVisibility(View.GONE);
}
} else if (value == PROGRESS_INDETERMINATE_ON) {
horizontalProgressBar.setIndeterminate(true);
} else if (value == PROGRESS_INDETERMINATE_OFF) {
horizontalProgressBar.setIndeterminate(false);
} 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.
horizontalProgressBar.setProgress(value - PROGRESS_START);
if (value < PROGRESS_END) {
showProgressBars(horizontalProgressBar, circularProgressBar);
} else {
hideProgressBars(horizontalProgressBar, circularProgressBar);
}
} else if (PROGRESS_SECONDARY_START <= value && value <= PROGRESS_SECONDARY_END) {
horizontalProgressBar.setSecondaryProgress(value - PROGRESS_SECONDARY_START);
showProgressBars(horizontalProgressBar, circularProgressBar);
}
}
private void showProgressBars(ProgressBar horizontalProgressBar, ProgressBar spinnyProgressBar) {
final int features = getLocalFeatures();
if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0 &&
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.getProgress() < 10000) {
horizontalProgressBar.setVisibility(View.VISIBLE);
}
}
private void hideProgressBars(ProgressBar horizontalProgressBar, ProgressBar spinnyProgressBar) {
final int features = getLocalFeatures();
Animation anim = AnimationUtils.loadAnimation(getContext(), com.android.internal.R.anim.fade_out);
anim.setDuration(1000);
if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0 &&
spinnyProgressBar.getVisibility() == View.VISIBLE) {
spinnyProgressBar.startAnimation(anim);
spinnyProgressBar.setVisibility(View.INVISIBLE);
}
if ((features & (1 << FEATURE_PROGRESS)) != 0 &&
horizontalProgressBar.getVisibility() == View.VISIBLE) {
horizontalProgressBar.startAnimation(anim);
horizontalProgressBar.setVisibility(View.INVISIBLE);
}
}
/**
* 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: {
// 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.
getAudioManager().handleKeyDown(event, mVolumeControlStreamType);
return true;
}
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:
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.
getAudioManager().handleKeyUp(event, mVolumeControlStreamType);
return true;
}
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();
}
return true;
}
}
return false;
}
@Override
protected void onActive() {
}
@Override
public final View getDecorView() {
if (mDecor == null) {
installDecor();
}
return mDecor;
}
@Override
public final View peekDecorView() {
return mDecor;
}
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