1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.view.menu;
18
19import android.content.Context;
20import android.content.res.Resources;
21import android.database.DataSetObserver;
22import android.os.Parcelable;
23import android.view.KeyEvent;
24import android.view.LayoutInflater;
25import android.view.MenuItem;
26import android.view.View;
27import android.view.View.MeasureSpec;
28import android.view.ViewGroup;
29import android.view.ViewTreeObserver;
30import android.widget.AdapterView;
31import android.widget.BaseAdapter;
32import android.widget.FrameLayout;
33import android.widget.ListAdapter;
34import android.widget.ListPopupWindow;
35import android.widget.PopupWindow;
36
37import java.util.ArrayList;
38
39/**
40 * Presents a menu as a small, simple popup anchored to another view.
41 * @hide
42 */
43public class MenuPopupHelper implements AdapterView.OnItemClickListener, View.OnKeyListener,
44        ViewTreeObserver.OnGlobalLayoutListener, PopupWindow.OnDismissListener,
45        View.OnAttachStateChangeListener, MenuPresenter {
46    private static final String TAG = "MenuPopupHelper";
47
48    static final int ITEM_LAYOUT = com.android.internal.R.layout.popup_menu_item_layout;
49
50    private Context mContext;
51    private LayoutInflater mInflater;
52    private ListPopupWindow mPopup;
53    private MenuBuilder mMenu;
54    private int mPopupMaxWidth;
55    private View mAnchorView;
56    private boolean mOverflowOnly;
57    private ViewTreeObserver mTreeObserver;
58
59    private MenuAdapter mAdapter;
60
61    private Callback mPresenterCallback;
62
63    boolean mForceShowIcon;
64
65    private ViewGroup mMeasureParent;
66
67    public MenuPopupHelper(Context context, MenuBuilder menu) {
68        this(context, menu, null, false);
69    }
70
71    public MenuPopupHelper(Context context, MenuBuilder menu, View anchorView) {
72        this(context, menu, anchorView, false);
73    }
74
75    public MenuPopupHelper(Context context, MenuBuilder menu,
76            View anchorView, boolean overflowOnly) {
77        mContext = context;
78        mInflater = LayoutInflater.from(context);
79        mMenu = menu;
80        mOverflowOnly = overflowOnly;
81
82        final Resources res = context.getResources();
83        mPopupMaxWidth = Math.max(res.getDisplayMetrics().widthPixels / 2,
84                res.getDimensionPixelSize(com.android.internal.R.dimen.config_prefDialogWidth));
85
86        mAnchorView = anchorView;
87
88        menu.addMenuPresenter(this);
89    }
90
91    public void setAnchorView(View anchor) {
92        mAnchorView = anchor;
93    }
94
95    public void setForceShowIcon(boolean forceShow) {
96        mForceShowIcon = forceShow;
97    }
98
99    public void show() {
100        if (!tryShow()) {
101            throw new IllegalStateException("MenuPopupHelper cannot be used without an anchor");
102        }
103    }
104
105    public boolean tryShow() {
106        mPopup = new ListPopupWindow(mContext, null, com.android.internal.R.attr.popupMenuStyle);
107        mPopup.setOnDismissListener(this);
108        mPopup.setOnItemClickListener(this);
109
110        mAdapter = new MenuAdapter(mMenu);
111        mPopup.setAdapter(mAdapter);
112        mPopup.setModal(true);
113
114        View anchor = mAnchorView;
115        if (anchor != null) {
116            final boolean addGlobalListener = mTreeObserver == null;
117            mTreeObserver = anchor.getViewTreeObserver(); // Refresh to latest
118            if (addGlobalListener) mTreeObserver.addOnGlobalLayoutListener(this);
119            anchor.addOnAttachStateChangeListener(this);
120            mPopup.setAnchorView(anchor);
121        } else {
122            return false;
123        }
124
125        mPopup.setContentWidth(Math.min(measureContentWidth(mAdapter), mPopupMaxWidth));
126        mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
127        mPopup.show();
128        mPopup.getListView().setOnKeyListener(this);
129        return true;
130    }
131
132    public void dismiss() {
133        if (isShowing()) {
134            mPopup.dismiss();
135        }
136    }
137
138    public void onDismiss() {
139        mPopup = null;
140        mMenu.close();
141        if (mTreeObserver != null) {
142            if (!mTreeObserver.isAlive()) mTreeObserver = mAnchorView.getViewTreeObserver();
143            mTreeObserver.removeGlobalOnLayoutListener(this);
144            mTreeObserver = null;
145        }
146        mAnchorView.removeOnAttachStateChangeListener(this);
147    }
148
149    public boolean isShowing() {
150        return mPopup != null && mPopup.isShowing();
151    }
152
153    @Override
154    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
155        MenuAdapter adapter = mAdapter;
156        adapter.mAdapterMenu.performItemAction(adapter.getItem(position), 0);
157    }
158
159    public boolean onKey(View v, int keyCode, KeyEvent event) {
160        if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_MENU) {
161            dismiss();
162            return true;
163        }
164        return false;
165    }
166
167    private int measureContentWidth(ListAdapter adapter) {
168        // Menus don't tend to be long, so this is more sane than it looks.
169        int width = 0;
170        View itemView = null;
171        int itemType = 0;
172        final int widthMeasureSpec =
173            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
174        final int heightMeasureSpec =
175            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
176        final int count = adapter.getCount();
177        for (int i = 0; i < count; i++) {
178            final int positionType = adapter.getItemViewType(i);
179            if (positionType != itemType) {
180                itemType = positionType;
181                itemView = null;
182            }
183            if (mMeasureParent == null) {
184                mMeasureParent = new FrameLayout(mContext);
185            }
186            itemView = adapter.getView(i, itemView, mMeasureParent);
187            itemView.measure(widthMeasureSpec, heightMeasureSpec);
188            width = Math.max(width, itemView.getMeasuredWidth());
189        }
190        return width;
191    }
192
193    @Override
194    public void onGlobalLayout() {
195        if (isShowing()) {
196            final View anchor = mAnchorView;
197            if (anchor == null || !anchor.isShown()) {
198                dismiss();
199            } else if (isShowing()) {
200                // Recompute window size and position
201                mPopup.show();
202            }
203        }
204    }
205
206    @Override
207    public void onViewAttachedToWindow(View v) {
208    }
209
210    @Override
211    public void onViewDetachedFromWindow(View v) {
212        if (mTreeObserver != null) {
213            if (!mTreeObserver.isAlive()) mTreeObserver = v.getViewTreeObserver();
214            mTreeObserver.removeGlobalOnLayoutListener(this);
215        }
216        v.removeOnAttachStateChangeListener(this);
217    }
218
219    @Override
220    public void initForMenu(Context context, MenuBuilder menu) {
221        // Don't need to do anything; we added as a presenter in the constructor.
222    }
223
224    @Override
225    public MenuView getMenuView(ViewGroup root) {
226        throw new UnsupportedOperationException("MenuPopupHelpers manage their own views");
227    }
228
229    @Override
230    public void updateMenuView(boolean cleared) {
231        if (mAdapter != null) mAdapter.notifyDataSetChanged();
232    }
233
234    @Override
235    public void setCallback(Callback cb) {
236        mPresenterCallback = cb;
237    }
238
239    @Override
240    public boolean onSubMenuSelected(SubMenuBuilder subMenu) {
241        if (subMenu.hasVisibleItems()) {
242            MenuPopupHelper subPopup = new MenuPopupHelper(mContext, subMenu, mAnchorView, false);
243            subPopup.setCallback(mPresenterCallback);
244
245            boolean preserveIconSpacing = false;
246            final int count = subMenu.size();
247            for (int i = 0; i < count; i++) {
248                MenuItem childItem = subMenu.getItem(i);
249                if (childItem.isVisible() && childItem.getIcon() != null) {
250                    preserveIconSpacing = true;
251                    break;
252                }
253            }
254            subPopup.setForceShowIcon(preserveIconSpacing);
255
256            if (subPopup.tryShow()) {
257                if (mPresenterCallback != null) {
258                    mPresenterCallback.onOpenSubMenu(subMenu);
259                }
260                return true;
261            }
262        }
263        return false;
264    }
265
266    @Override
267    public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
268        // Only care about the (sub)menu we're presenting.
269        if (menu != mMenu) return;
270
271        dismiss();
272        if (mPresenterCallback != null) {
273            mPresenterCallback.onCloseMenu(menu, allMenusAreClosing);
274        }
275    }
276
277    @Override
278    public boolean flagActionItems() {
279        return false;
280    }
281
282    public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) {
283        return false;
284    }
285
286    public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) {
287        return false;
288    }
289
290    @Override
291    public int getId() {
292        return 0;
293    }
294
295    @Override
296    public Parcelable onSaveInstanceState() {
297        return null;
298    }
299
300    @Override
301    public void onRestoreInstanceState(Parcelable state) {
302    }
303
304    private class MenuAdapter extends BaseAdapter {
305        private MenuBuilder mAdapterMenu;
306        private int mExpandedIndex = -1;
307
308        public MenuAdapter(MenuBuilder menu) {
309            mAdapterMenu = menu;
310            findExpandedIndex();
311        }
312
313        public int getCount() {
314            ArrayList<MenuItemImpl> items = mOverflowOnly ?
315                    mAdapterMenu.getNonActionItems() : mAdapterMenu.getVisibleItems();
316            if (mExpandedIndex < 0) {
317                return items.size();
318            }
319            return items.size() - 1;
320        }
321
322        public MenuItemImpl getItem(int position) {
323            ArrayList<MenuItemImpl> items = mOverflowOnly ?
324                    mAdapterMenu.getNonActionItems() : mAdapterMenu.getVisibleItems();
325            if (mExpandedIndex >= 0 && position >= mExpandedIndex) {
326                position++;
327            }
328            return items.get(position);
329        }
330
331        public long getItemId(int position) {
332            // Since a menu item's ID is optional, we'll use the position as an
333            // ID for the item in the AdapterView
334            return position;
335        }
336
337        public View getView(int position, View convertView, ViewGroup parent) {
338            if (convertView == null) {
339                convertView = mInflater.inflate(ITEM_LAYOUT, parent, false);
340            }
341
342            MenuView.ItemView itemView = (MenuView.ItemView) convertView;
343            if (mForceShowIcon) {
344                ((ListMenuItemView) convertView).setForceShowIcon(true);
345            }
346            itemView.initialize(getItem(position), 0);
347            return convertView;
348        }
349
350        void findExpandedIndex() {
351            final MenuItemImpl expandedItem = mMenu.getExpandedItem();
352            if (expandedItem != null) {
353                final ArrayList<MenuItemImpl> items = mMenu.getNonActionItems();
354                final int count = items.size();
355                for (int i = 0; i < count; i++) {
356                    final MenuItemImpl item = items.get(i);
357                    if (item == expandedItem) {
358                        mExpandedIndex = i;
359                        return;
360                    }
361                }
362            }
363            mExpandedIndex = -1;
364        }
365
366        @Override
367        public void notifyDataSetChanged() {
368            findExpandedIndex();
369            super.notifyDataSetChanged();
370        }
371    }
372}
373