2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.browser;
19 import android.app.Activity;
20 import android.app.ExpandableListActivity;
21 import android.content.Intent;
22 import android.content.pm.PackageManager;
23 import android.content.pm.ResolveInfo;
24 import android.database.ContentObserver;
25 import android.database.Cursor;
26 import android.database.DataSetObserver;
27 import android.graphics.Bitmap;
28 import android.os.Bundle;
29 import android.os.Handler;
30 import android.os.ServiceManager;
31 import android.provider.Browser;
32 import android.text.IClipboard;
33 import android.util.Log;
34 import android.view.ContextMenu;
35 import android.view.KeyEvent;
36 import android.view.LayoutInflater;
37 import android.view.Menu;
38 import android.view.MenuInflater;
39 import android.view.MenuItem;
40 import android.view.View;
41 import android.view.ViewGroup;
42 import android.view.ViewGroup.LayoutParams;
43 import android.view.ContextMenu.ContextMenuInfo;
44 import android.view.ViewStub;
45 import android.webkit.DateSorter;
46 import android.webkit.WebIconDatabase.IconListener;
47 import android.widget.AdapterView;
48 import android.widget.ExpandableListAdapter;
49 import android.widget.ExpandableListView;
50 import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
51 import android.widget.TextView;
52 import android.widget.Toast;
54 import java.util.List;
55 import java.util.Vector;
58 * Activity for displaying the browser's history, divided into
61 public class BrowserHistoryPage extends ExpandableListActivity {
62 private HistoryAdapter mAdapter;
63 private DateSorter mDateSorter;
64 private boolean mMaxTabsOpen;
65 private HistoryItem mContextHeader;
67 private final static String LOGTAG = "browser";
69 // Implementation of WebIconDatabase.IconListener
70 private class IconReceiver implements IconListener {
71 public void onReceivedIcon(String url, Bitmap icon) {
72 setListAdapter(mAdapter);
75 // Instance of IconReceiver
76 private final IconReceiver mIconReceiver = new IconReceiver();
79 * Report back to the calling activity to load a site.
80 * @param url Site to load.
81 * @param newWindow True if the URL should be loaded in a new window
83 private void loadUrl(String url, boolean newWindow) {
84 Intent intent = new Intent().setAction(url);
86 Bundle b = new Bundle();
87 b.putBoolean("new_window", true);
90 setResultToParent(RESULT_OK, intent);
94 private void copy(CharSequence text) {
96 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
98 clip.setClipboardText(text);
100 } catch (android.os.RemoteException e) {
101 Log.e(LOGTAG, "Copy failed", e);
106 protected void onCreate(Bundle icicle) {
107 super.onCreate(icicle);
108 setTitle(R.string.browser_history);
110 mDateSorter = new DateSorter(this);
112 mAdapter = new HistoryAdapter();
113 setListAdapter(mAdapter);
114 final ExpandableListView list = getExpandableListView();
115 list.setOnCreateContextMenuListener(this);
116 View v = new ViewStub(this, R.layout.empty_history);
117 addContentView(v, new LayoutParams(LayoutParams.FILL_PARENT,
118 LayoutParams.FILL_PARENT));
119 list.setEmptyView(v);
120 // Do not post the runnable if there is nothing in the list.
121 if (list.getExpandableListAdapter().getGroupCount() > 0) {
122 list.post(new Runnable() {
124 // In case the history gets cleared before this event
126 if (list.getExpandableListAdapter().getGroupCount() > 0) {
132 mMaxTabsOpen = getIntent().getBooleanExtra("maxTabsOpen", false);
133 CombinedBookmarkHistoryActivity.getIconListenerSet(getContentResolver())
134 .addListener(mIconReceiver);
136 // initialize the result to canceled, so that if the user just presses
137 // back then it will have the correct result
138 setResultToParent(RESULT_CANCELED, null);
142 public boolean onCreateOptionsMenu(Menu menu) {
143 super.onCreateOptionsMenu(menu);
144 MenuInflater inflater = getMenuInflater();
145 inflater.inflate(R.menu.history, menu);
150 public boolean onPrepareOptionsMenu(Menu menu) {
151 menu.findItem(R.id.clear_history_menu_id).setVisible(Browser.canClearHistory(this.getContentResolver()));
156 public boolean onOptionsItemSelected(MenuItem item) {
157 switch (item.getItemId()) {
158 case R.id.clear_history_menu_id:
159 // FIXME: Need to clear the tab control in browserActivity
161 Browser.clearHistory(getContentResolver());
162 mAdapter.refreshData();
168 return super.onOptionsItemSelected(item);
172 public void onCreateContextMenu(ContextMenu menu, View v,
173 ContextMenuInfo menuInfo) {
174 ExpandableListContextMenuInfo i =
175 (ExpandableListContextMenuInfo) menuInfo;
176 // Do not allow a context menu to come up from the group views.
177 if (!(i.targetView instanceof HistoryItem)) {
182 MenuInflater inflater = getMenuInflater();
183 inflater.inflate(R.menu.historycontext, menu);
185 HistoryItem historyItem = (HistoryItem) i.targetView;
188 if (mContextHeader == null) {
189 mContextHeader = new HistoryItem(this);
190 } else if (mContextHeader.getParent() != null) {
191 ((ViewGroup) mContextHeader.getParent()).removeView(mContextHeader);
193 historyItem.copyTo(mContextHeader);
194 menu.setHeaderView(mContextHeader);
196 // Only show open in new tab if we have not maxed out available tabs
197 menu.findItem(R.id.new_window_context_menu_id).setVisible(!mMaxTabsOpen);
199 // For a bookmark, provide the option to remove it from bookmarks
200 if (historyItem.isBookmark()) {
201 MenuItem item = menu.findItem(R.id.save_to_bookmarks_menu_id);
202 item.setTitle(R.string.remove_from_bookmarks);
204 // decide whether to show the share link option
205 PackageManager pm = getPackageManager();
206 Intent send = new Intent(Intent.ACTION_SEND);
207 send.setType("text/plain");
208 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
209 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
211 super.onCreateContextMenu(menu, v, menuInfo);
215 public boolean onContextItemSelected(MenuItem item) {
216 ExpandableListContextMenuInfo i =
217 (ExpandableListContextMenuInfo) item.getMenuInfo();
218 HistoryItem historyItem = (HistoryItem) i.targetView;
219 String url = historyItem.getUrl();
220 String title = historyItem.getName();
221 switch (item.getItemId()) {
222 case R.id.open_context_menu_id:
225 case R.id.new_window_context_menu_id:
228 case R.id.save_to_bookmarks_menu_id:
229 if (historyItem.isBookmark()) {
230 Bookmarks.removeFromBookmarks(this, getContentResolver(),
233 Browser.saveBookmark(this, title, url);
236 case R.id.share_link_context_menu_id:
237 Browser.sendString(this, url);
239 case R.id.copy_url_context_menu_id:
242 case R.id.delete_context_menu_id:
243 Browser.deleteFromHistory(getContentResolver(), url);
244 mAdapter.refreshData();
246 case R.id.homepage_context_menu_id:
247 BrowserSettings.getInstance().setHomePage(this, url);
248 Toast.makeText(this, R.string.homepage_set,
249 Toast.LENGTH_LONG).show();
254 return super.onContextItemSelected(item);
258 public boolean onChildClick(ExpandableListView parent, View v,
259 int groupPosition, int childPosition, long id) {
260 if (v instanceof HistoryItem) {
261 loadUrl(((HistoryItem) v).getUrl(), false);
267 // This Activity is generally a sub-Activity of CombinedHistoryActivity. In
268 // that situation, we need to pass our result code up to our parent.
269 // However, if someone calls this Activity directly, then this has no
270 // parent, and it needs to set it on itself.
271 private void setResultToParent(int resultCode, Intent data) {
272 Activity a = getParent() == null ? this : getParent();
273 a.setResult(resultCode, data);
276 private class ChangeObserver extends ContentObserver {
277 public ChangeObserver() {
278 super(new Handler());
282 public boolean deliverSelfNotifications() {
287 public void onChange(boolean selfChange) {
288 mAdapter.refreshData();
292 private class HistoryAdapter implements ExpandableListAdapter {
294 // Array for each of our bins. Each entry represents how many items are
296 private int mItemMap[];
297 // This is our GroupCount. We will have at most DateSorter.DAY_COUNT
298 // bins, less if the user has no items in one or more bins.
299 private int mNumberOfBins;
300 private Vector<DataSetObserver> mObservers;
301 private Cursor mCursor;
304 mObservers = new Vector<DataSetObserver>();
306 final String whereClause = Browser.BookmarkColumns.VISITS + " > 0"
307 // In AddBookmarkPage, where we save new bookmarks, we add
308 // three visits to newly created bookmarks, so that
309 // bookmarks that have not been visited will show up in the
310 // most visited, and higher in the goto search box.
311 // However, this puts the site in the history, unless we
312 // ignore sites with a DATE of 0, which the next line does.
313 + " AND " + Browser.BookmarkColumns.DATE + " > 0";
314 final String orderBy = Browser.BookmarkColumns.DATE + " DESC";
316 mCursor = managedQuery(
317 Browser.BOOKMARKS_URI,
318 Browser.HISTORY_PROJECTION,
319 whereClause, null, orderBy);
322 mCursor.registerContentObserver(new ChangeObserver());
326 if (mCursor.isClosed()) {
331 for (DataSetObserver o : mObservers) {
336 private void buildMap() {
337 // The cursor is sorted by date
338 // The ItemMap will store the number of items in each bin.
339 int array[] = new int[DateSorter.DAY_COUNT];
340 // Zero out the array.
341 for (int j = 0; j < DateSorter.DAY_COUNT; j++) {
346 if (mCursor.moveToFirst() && mCursor.getCount() > 0) {
347 while (!mCursor.isAfterLast()) {
348 long date = mCursor.getLong(Browser.HISTORY_PROJECTION_DATE_INDEX);
349 int index = mDateSorter.getIndex(date);
350 if (index > dateIndex) {
352 if (index == DateSorter.DAY_COUNT - 1) {
353 // We are already in the last bin, so it will
354 // include all the remaining items
355 array[index] = mCursor.getCount()
356 - mCursor.getPosition();
362 mCursor.moveToNext();
368 // This translates from a group position in the Adapter to a position in
369 // our array. This is necessary because some positions in the array
370 // have no history items, so we simply do not present those positions
372 private int groupPositionToArrayPosition(int groupPosition) {
373 if (groupPosition < 0 || groupPosition >= DateSorter.DAY_COUNT) {
374 throw new AssertionError("group position out of range");
376 if (DateSorter.DAY_COUNT == mNumberOfBins || 0 == mNumberOfBins) {
377 // In the first case, we have exactly the same number of bins
378 // as our maximum possible, so there is no need to do a
380 // The second statement is in case this method gets called when
381 // the array is empty, in which case the provided groupPosition
383 return groupPosition;
385 int arrayPosition = -1;
386 while (groupPosition > -1) {
388 if (mItemMap[arrayPosition] != 0) {
392 return arrayPosition;
395 public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
396 View convertView, ViewGroup parent) {
397 groupPosition = groupPositionToArrayPosition(groupPosition);
399 if (null == convertView || !(convertView instanceof HistoryItem)) {
400 item = new HistoryItem(BrowserHistoryPage.this);
401 // Add padding on the left so it will be indented from the
402 // arrows on the group views.
403 item.setPadding(item.getPaddingLeft() + 10,
404 item.getPaddingTop(),
405 item.getPaddingRight(),
406 item.getPaddingBottom());
408 item = (HistoryItem) convertView;
410 int index = childPosition;
411 for (int i = 0; i < groupPosition; i++) {
412 index += mItemMap[i];
414 mCursor.moveToPosition(index);
415 item.setName(mCursor.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX));
416 String url = mCursor.getString(Browser.HISTORY_PROJECTION_URL_INDEX);
418 item.setFavicon(CombinedBookmarkHistoryActivity.getIconListenerSet(
419 getContentResolver()).getFavicon(url));
420 item.setIsBookmark(1 ==
421 mCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX));
425 public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
426 groupPosition = groupPositionToArrayPosition(groupPosition);
428 if (null == convertView || !(convertView instanceof TextView)) {
429 LayoutInflater factory =
430 LayoutInflater.from(BrowserHistoryPage.this);
432 factory.inflate(R.layout.history_header, null);
434 item = (TextView) convertView;
436 item.setText(mDateSorter.getLabel(groupPosition));
440 public boolean areAllItemsEnabled() {
444 public boolean isChildSelectable(int groupPosition, int childPosition) {
448 public int getGroupCount() {
449 return mNumberOfBins;
452 public int getChildrenCount(int groupPosition) {
453 return mItemMap[groupPositionToArrayPosition(groupPosition)];
456 public Object getGroup(int groupPosition) {
460 public Object getChild(int groupPosition, int childPosition) {
464 public long getGroupId(int groupPosition) {
465 return groupPosition;
468 public long getChildId(int groupPosition, int childPosition) {
469 return (childPosition << 3) + groupPosition;
472 public boolean hasStableIds() {
476 public void registerDataSetObserver(DataSetObserver observer) {
477 mObservers.add(observer);
480 public void unregisterDataSetObserver(DataSetObserver observer) {
481 mObservers.remove(observer);
484 public void onGroupExpanded(int groupPosition) {
488 public void onGroupCollapsed(int groupPosition) {
492 public long getCombinedChildId(long groupId, long childId) {
496 public long getCombinedGroupId(long groupId) {
500 public boolean isEmpty() {
501 return mCursor.getCount() == 0;