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;
66 private final static String LOGTAG = "browser";
68 // Implementation of WebIconDatabase.IconListener
69 private class IconReceiver implements IconListener {
70 public void onReceivedIcon(String url, Bitmap icon) {
71 setListAdapter(mAdapter);
74 // Instance of IconReceiver
75 private final IconReceiver mIconReceiver = new IconReceiver();
78 * Report back to the calling activity to load a site.
79 * @param url Site to load.
80 * @param newWindow True if the URL should be loaded in a new window
82 private void loadUrl(String url, boolean newWindow) {
83 Intent intent = new Intent().setAction(url);
85 Bundle b = new Bundle();
86 b.putBoolean("new_window", true);
89 setResultToParent(RESULT_OK, intent);
93 private void copy(CharSequence text) {
95 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
97 clip.setClipboardText(text);
99 } catch (android.os.RemoteException e) {
100 Log.e(LOGTAG, "Copy failed", e);
105 protected void onCreate(Bundle icicle) {
106 super.onCreate(icicle);
107 setTitle(R.string.browser_history);
109 mDateSorter = new DateSorter(this);
111 mAdapter = new HistoryAdapter();
112 setListAdapter(mAdapter);
113 final ExpandableListView list = getExpandableListView();
114 list.setOnCreateContextMenuListener(this);
115 View v = new ViewStub(this, R.layout.empty_history);
116 addContentView(v, new LayoutParams(LayoutParams.FILL_PARENT,
117 LayoutParams.FILL_PARENT));
118 list.setEmptyView(v);
119 // Do not post the runnable if there is nothing in the list.
120 if (list.getExpandableListAdapter().getGroupCount() > 0) {
121 list.post(new Runnable() {
123 // In case the history gets cleared before this event
125 if (list.getExpandableListAdapter().getGroupCount() > 0) {
131 mMaxTabsOpen = getIntent().getBooleanExtra("maxTabsOpen", false);
132 CombinedBookmarkHistoryActivity.getIconListenerSet(getContentResolver())
133 .addListener(mIconReceiver);
135 // initialize the result to canceled, so that if the user just presses
136 // back then it will have the correct result
137 setResultToParent(RESULT_CANCELED, null);
141 public boolean onCreateOptionsMenu(Menu menu) {
142 super.onCreateOptionsMenu(menu);
143 MenuInflater inflater = getMenuInflater();
144 inflater.inflate(R.menu.history, menu);
149 public boolean onPrepareOptionsMenu(Menu menu) {
150 menu.findItem(R.id.clear_history_menu_id).setVisible(Browser.canClearHistory(this.getContentResolver()));
155 public boolean onOptionsItemSelected(MenuItem item) {
156 switch (item.getItemId()) {
157 case R.id.clear_history_menu_id:
158 // FIXME: Need to clear the tab control in browserActivity
160 Browser.clearHistory(getContentResolver());
161 mAdapter.refreshData();
167 return super.onOptionsItemSelected(item);
171 public void onCreateContextMenu(ContextMenu menu, View v,
172 ContextMenuInfo menuInfo) {
173 ExpandableListContextMenuInfo i =
174 (ExpandableListContextMenuInfo) menuInfo;
175 // Do not allow a context menu to come up from the group views.
176 if (!(i.targetView instanceof HistoryItem)) {
181 MenuInflater inflater = getMenuInflater();
182 inflater.inflate(R.menu.historycontext, menu);
185 menu.setHeaderTitle(((HistoryItem)i.targetView).getUrl());
187 // Only show open in new tab if we have not maxed out available tabs
188 menu.findItem(R.id.new_window_context_menu_id).setVisible(!mMaxTabsOpen);
190 // decide whether to show the share link option
191 PackageManager pm = getPackageManager();
192 Intent send = new Intent(Intent.ACTION_SEND);
193 send.setType("text/plain");
194 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
195 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
197 super.onCreateContextMenu(menu, v, menuInfo);
201 public boolean onContextItemSelected(MenuItem item) {
202 ExpandableListContextMenuInfo i =
203 (ExpandableListContextMenuInfo) item.getMenuInfo();
204 String url = ((HistoryItem)i.targetView).getUrl();
205 String title = ((HistoryItem)i.targetView).getName();
206 switch (item.getItemId()) {
207 case R.id.open_context_menu_id:
210 case R.id.new_window_context_menu_id:
213 case R.id.save_to_bookmarks_menu_id:
214 Browser.saveBookmark(this, title, url);
216 case R.id.share_link_context_menu_id:
217 Browser.sendString(this, url);
219 case R.id.copy_context_menu_id:
222 case R.id.delete_context_menu_id:
223 Browser.deleteFromHistory(getContentResolver(), url);
224 mAdapter.refreshData();
226 case R.id.homepage_context_menu_id:
227 BrowserSettings.getInstance().setHomePage(this, url);
228 Toast.makeText(this, R.string.homepage_set,
229 Toast.LENGTH_LONG).show();
234 return super.onContextItemSelected(item);
238 public boolean onChildClick(ExpandableListView parent, View v,
239 int groupPosition, int childPosition, long id) {
240 if (v instanceof HistoryItem) {
241 loadUrl(((HistoryItem) v).getUrl(), false);
247 // This Activity is generally a sub-Activity of CombinedHistoryActivity. In
248 // that situation, we need to pass our result code up to our parent.
249 // However, if someone calls this Activity directly, then this has no
250 // parent, and it needs to set it on itself.
251 private void setResultToParent(int resultCode, Intent data) {
252 Activity a = getParent() == null ? this : getParent();
253 a.setResult(resultCode, data);
256 private class ChangeObserver extends ContentObserver {
257 public ChangeObserver() {
258 super(new Handler());
262 public boolean deliverSelfNotifications() {
267 public void onChange(boolean selfChange) {
268 mAdapter.refreshData();
272 private class HistoryAdapter implements ExpandableListAdapter {
274 // Array for each of our bins. Each entry represents how many items are
276 private int mItemMap[];
277 // This is our GroupCount. We will have at most DateSorter.DAY_COUNT
278 // bins, less if the user has no items in one or more bins.
279 private int mNumberOfBins;
280 private Vector<DataSetObserver> mObservers;
281 private Cursor mCursor;
284 mObservers = new Vector<DataSetObserver>();
286 final String whereClause = Browser.BookmarkColumns.VISITS + " > 0"
287 // In AddBookmarkPage, where we save new bookmarks, we add
288 // three visits to newly created bookmarks, so that
289 // bookmarks that have not been visited will show up in the
290 // most visited, and higher in the goto search box.
291 // However, this puts the site in the history, unless we
292 // ignore sites with a DATE of 0, which the next line does.
293 + " AND " + Browser.BookmarkColumns.DATE + " > 0";
294 final String orderBy = Browser.BookmarkColumns.DATE + " DESC";
296 mCursor = managedQuery(
297 Browser.BOOKMARKS_URI,
298 Browser.HISTORY_PROJECTION,
299 whereClause, null, orderBy);
302 mCursor.registerContentObserver(new ChangeObserver());
308 for (DataSetObserver o : mObservers) {
313 private void buildMap() {
314 // The cursor is sorted by date
315 // The ItemMap will store the number of items in each bin.
316 int array[] = new int[DateSorter.DAY_COUNT];
317 // Zero out the array.
318 for (int j = 0; j < DateSorter.DAY_COUNT; j++) {
323 if (mCursor.moveToFirst() && mCursor.getCount() > 0) {
324 while (!mCursor.isAfterLast()) {
325 long date = mCursor.getLong(Browser.HISTORY_PROJECTION_DATE_INDEX);
326 int index = mDateSorter.getIndex(date);
327 if (index > dateIndex) {
329 if (index == DateSorter.DAY_COUNT - 1) {
330 // We are already in the last bin, so it will
331 // include all the remaining items
332 array[index] = mCursor.getCount()
333 - mCursor.getPosition();
339 mCursor.moveToNext();
345 // This translates from a group position in the Adapter to a position in
346 // our array. This is necessary because some positions in the array
347 // have no history items, so we simply do not present those positions
349 private int groupPositionToArrayPosition(int groupPosition) {
350 if (groupPosition < 0 || groupPosition >= DateSorter.DAY_COUNT) {
351 throw new AssertionError("group position out of range");
353 if (DateSorter.DAY_COUNT == mNumberOfBins || 0 == mNumberOfBins) {
354 // In the first case, we have exactly the same number of bins
355 // as our maximum possible, so there is no need to do a
357 // The second statement is in case this method gets called when
358 // the array is empty, in which case the provided groupPosition
360 return groupPosition;
362 int arrayPosition = -1;
363 while (groupPosition > -1) {
365 if (mItemMap[arrayPosition] != 0) {
369 return arrayPosition;
372 public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
373 View convertView, ViewGroup parent) {
374 groupPosition = groupPositionToArrayPosition(groupPosition);
376 if (null == convertView || !(convertView instanceof HistoryItem)) {
377 item = new HistoryItem(BrowserHistoryPage.this);
378 // Add padding on the left so it will be indented from the
379 // arrows on the group views.
380 item.setPadding(item.getPaddingLeft() + 10,
381 item.getPaddingTop(),
382 item.getPaddingRight(),
383 item.getPaddingBottom());
385 item = (HistoryItem) convertView;
387 int index = childPosition;
388 for (int i = 0; i < groupPosition; i++) {
389 index += mItemMap[i];
391 mCursor.moveToPosition(index);
392 item.setName(mCursor.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX));
393 String url = mCursor.getString(Browser.HISTORY_PROJECTION_URL_INDEX);
395 item.setFavicon(CombinedBookmarkHistoryActivity.getIconListenerSet(
396 getContentResolver()).getFavicon(url));
397 item.setIsBookmark(1 ==
398 mCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX));
402 public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
403 groupPosition = groupPositionToArrayPosition(groupPosition);
405 if (null == convertView || !(convertView instanceof TextView)) {
406 LayoutInflater factory =
407 LayoutInflater.from(BrowserHistoryPage.this);
409 factory.inflate(R.layout.history_header, null);
411 item = (TextView) convertView;
413 item.setText(mDateSorter.getLabel(groupPosition));
417 public boolean areAllItemsEnabled() {
421 public boolean isChildSelectable(int groupPosition, int childPosition) {
425 public int getGroupCount() {
426 return mNumberOfBins;
429 public int getChildrenCount(int groupPosition) {
430 return mItemMap[groupPositionToArrayPosition(groupPosition)];
433 public Object getGroup(int groupPosition) {
437 public Object getChild(int groupPosition, int childPosition) {
441 public long getGroupId(int groupPosition) {
442 return groupPosition;
445 public long getChildId(int groupPosition, int childPosition) {
446 return (childPosition << 3) + groupPosition;
449 public boolean hasStableIds() {
453 public void registerDataSetObserver(DataSetObserver observer) {
454 mObservers.add(observer);
457 public void unregisterDataSetObserver(DataSetObserver observer) {
458 mObservers.remove(observer);
461 public void onGroupExpanded(int groupPosition) {
465 public void onGroupCollapsed(int groupPosition) {
469 public long getCombinedChildId(long groupId, long childId) {
473 public long getCombinedGroupId(long groupId) {
477 public boolean isEmpty() {
478 return mCursor.getCount() == 0;