OSDN Git Service

Merge commit '60c8c06e' into manualmerge
[android-x86/packages-apps-Browser.git] / src / com / android / browser / BrowserHistoryPage.java
1 /*
2  * Copyright (C) 2008 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
17 package com.android.browser;
18
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;
53
54 import java.util.List;
55 import java.util.Vector;
56
57 /**
58  * Activity for displaying the browser's history, divided into
59  * days of viewing.
60  */
61 public class BrowserHistoryPage extends ExpandableListActivity {
62     private HistoryAdapter          mAdapter;
63     private DateSorter              mDateSorter;
64     private boolean                 mMaxTabsOpen;
65     private HistoryItem             mContextHeader;
66
67     private final static String LOGTAG = "browser";
68
69     // Implementation of WebIconDatabase.IconListener
70     private class IconReceiver implements IconListener {
71         public void onReceivedIcon(String url, Bitmap icon) {
72             setListAdapter(mAdapter);
73         }
74     }
75     // Instance of IconReceiver
76     private final IconReceiver mIconReceiver = new IconReceiver();
77
78     /**
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
82      */
83     private void loadUrl(String url, boolean newWindow) {
84         Intent intent = new Intent().setAction(url);
85         if (newWindow) {
86             Bundle b = new Bundle();
87             b.putBoolean("new_window", true);
88             intent.putExtras(b);
89         }
90         setResultToParent(RESULT_OK, intent);
91         finish();
92     }
93     
94     private void copy(CharSequence text) {
95         try {
96             IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
97             if (clip != null) {
98                 clip.setClipboardText(text);
99             }
100         } catch (android.os.RemoteException e) {
101             Log.e(LOGTAG, "Copy failed", e);
102         }
103     }
104
105     @Override
106     protected void onCreate(Bundle icicle) {
107         super.onCreate(icicle);
108         setTitle(R.string.browser_history);
109         
110         mDateSorter = new DateSorter(this);
111
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() {
123                 public void run() {
124                     // In case the history gets cleared before this event
125                     // happens.
126                     if (list.getExpandableListAdapter().getGroupCount() > 0) {
127                         list.expandGroup(0);
128                     }
129                 }
130             });
131         }
132         mMaxTabsOpen = getIntent().getBooleanExtra("maxTabsOpen", false);
133         CombinedBookmarkHistoryActivity.getIconListenerSet(getContentResolver())
134                 .addListener(mIconReceiver);
135         
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);
139     }
140
141     @Override
142     public boolean onCreateOptionsMenu(Menu menu) {
143         super.onCreateOptionsMenu(menu);
144         MenuInflater inflater = getMenuInflater();
145         inflater.inflate(R.menu.history, menu);
146         return true;
147     }
148
149     @Override
150     public boolean onPrepareOptionsMenu(Menu menu) {
151         menu.findItem(R.id.clear_history_menu_id).setVisible(Browser.canClearHistory(this.getContentResolver()));
152         return true;
153     }
154     
155     @Override
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 
160                 // as well
161                 Browser.clearHistory(getContentResolver());
162                 mAdapter.refreshData();
163                 return true;
164                 
165             default:
166                 break;
167         }  
168         return super.onOptionsItemSelected(item);
169     }
170
171     @Override
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)) {
178             return;
179         }
180
181         // Inflate the menu
182         MenuInflater inflater = getMenuInflater();
183         inflater.inflate(R.menu.historycontext, menu);
184
185         HistoryItem historyItem = (HistoryItem) i.targetView;
186
187         // Setup the header
188         if (mContextHeader == null) {
189             mContextHeader = new HistoryItem(this);
190         } else if (mContextHeader.getParent() != null) {
191             ((ViewGroup) mContextHeader.getParent()).removeView(mContextHeader);
192         }
193         historyItem.copyTo(mContextHeader);
194         menu.setHeaderView(mContextHeader);
195
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);
198         
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);
203         }
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);
210         
211         super.onCreateContextMenu(menu, v, menuInfo);
212     }
213     
214     @Override
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:
223                 loadUrl(url, false);
224                 return true;
225             case R.id.new_window_context_menu_id:
226                 loadUrl(url, true);
227                 return true;
228             case R.id.save_to_bookmarks_menu_id:
229                 if (historyItem.isBookmark()) {
230                     Bookmarks.removeFromBookmarks(this, getContentResolver(),
231                             url);
232                 } else {
233                     Browser.saveBookmark(this, title, url);
234                 }
235                 return true;
236             case R.id.share_link_context_menu_id:
237                 Browser.sendString(this, url);
238                 return true;
239             case R.id.copy_url_context_menu_id:
240                 copy(url);
241                 return true;
242             case R.id.delete_context_menu_id:
243                 Browser.deleteFromHistory(getContentResolver(), url);
244                 mAdapter.refreshData();
245                 return true;
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();
250                 return true;
251             default:
252                 break;
253         }
254         return super.onContextItemSelected(item);
255     }
256     
257     @Override
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);
262             return true;
263         }
264         return false;
265     }
266
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);
274     }
275
276     private class ChangeObserver extends ContentObserver {
277         public ChangeObserver() {
278             super(new Handler());
279         }
280
281         @Override
282         public boolean deliverSelfNotifications() {
283             return true;
284         }
285
286         @Override
287         public void onChange(boolean selfChange) {
288             mAdapter.refreshData();
289         }
290     }
291     
292     private class HistoryAdapter implements ExpandableListAdapter {
293         
294         // Array for each of our bins.  Each entry represents how many items are
295         // in that bin.
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;
302         
303         HistoryAdapter() {
304             mObservers = new Vector<DataSetObserver>();
305             
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";
315            
316             mCursor = managedQuery(
317                     Browser.BOOKMARKS_URI,
318                     Browser.HISTORY_PROJECTION,
319                     whereClause, null, orderBy);
320             
321             buildMap();
322             mCursor.registerContentObserver(new ChangeObserver());
323         }
324         
325         void refreshData() {
326             if (mCursor.isClosed()) {
327                 return;
328             }
329             mCursor.requery();
330             buildMap();
331             for (DataSetObserver o : mObservers) {
332                 o.onChanged();
333             }
334         }
335         
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++) {
342                 array[j] = 0;
343             }
344             mNumberOfBins = 0;
345             int dateIndex = -1;
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) {
351                         mNumberOfBins++;
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();
357                             break;
358                         }
359                         dateIndex = index;
360                     }
361                     array[dateIndex]++;
362                     mCursor.moveToNext();
363                 }
364             }
365             mItemMap = array;
366         }
367
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
371         // to the Adapter.
372         private int groupPositionToArrayPosition(int groupPosition) {
373             if (groupPosition < 0 || groupPosition >= DateSorter.DAY_COUNT) {
374                 throw new AssertionError("group position out of range");
375             }
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
379                 // conversion
380                 // The second statement is in case this method gets called when
381                 // the array is empty, in which case the provided groupPosition
382                 // will do fine.
383                 return groupPosition;
384             }
385             int arrayPosition = -1;
386             while (groupPosition > -1) {
387                 arrayPosition++;
388                 if (mItemMap[arrayPosition] != 0) {
389                     groupPosition--;
390                 }
391             }
392             return arrayPosition;
393         }
394
395         public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
396                 View convertView, ViewGroup parent) {
397             groupPosition = groupPositionToArrayPosition(groupPosition);
398             HistoryItem item;
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());
407             } else {
408                 item = (HistoryItem) convertView;
409             }
410             int index = childPosition;
411             for (int i = 0; i < groupPosition; i++) {
412                 index += mItemMap[i];
413             }
414             mCursor.moveToPosition(index);
415             item.setName(mCursor.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX));
416             String url = mCursor.getString(Browser.HISTORY_PROJECTION_URL_INDEX);
417             item.setUrl(url);
418             item.setFavicon(CombinedBookmarkHistoryActivity.getIconListenerSet(
419                     getContentResolver()).getFavicon(url));
420             item.setIsBookmark(1 ==
421                     mCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX));
422             return item;
423         }
424         
425         public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
426             groupPosition = groupPositionToArrayPosition(groupPosition);
427             TextView item;
428             if (null == convertView || !(convertView instanceof TextView)) {
429                 LayoutInflater factory = 
430                         LayoutInflater.from(BrowserHistoryPage.this);
431                 item = (TextView) 
432                         factory.inflate(R.layout.history_header, null);
433             } else {
434                 item = (TextView) convertView;
435             }
436             item.setText(mDateSorter.getLabel(groupPosition));
437             return item;
438         }
439
440         public boolean areAllItemsEnabled() {
441             return true;
442         }
443
444         public boolean isChildSelectable(int groupPosition, int childPosition) {
445             return true;
446         }
447
448         public int getGroupCount() {
449             return mNumberOfBins;
450         }
451
452         public int getChildrenCount(int groupPosition) {
453             return mItemMap[groupPositionToArrayPosition(groupPosition)];
454         }
455
456         public Object getGroup(int groupPosition) {
457             return null;
458         }
459
460         public Object getChild(int groupPosition, int childPosition) {
461             return null;
462         }
463
464         public long getGroupId(int groupPosition) {
465             return groupPosition;
466         }
467
468         public long getChildId(int groupPosition, int childPosition) {
469             return (childPosition << 3) + groupPosition;
470         }
471
472         public boolean hasStableIds() {
473             return true;
474         }
475
476         public void registerDataSetObserver(DataSetObserver observer) {
477             mObservers.add(observer);
478         }
479
480         public void unregisterDataSetObserver(DataSetObserver observer) {
481             mObservers.remove(observer);
482         }
483
484         public void onGroupExpanded(int groupPosition) {
485         
486         }
487
488         public void onGroupCollapsed(int groupPosition) {
489         
490         }
491
492         public long getCombinedChildId(long groupId, long childId) {
493             return childId;
494         }
495
496         public long getCombinedGroupId(long groupId) {
497             return groupId;
498         }
499
500         public boolean isEmpty() {
501             return mCursor.getCount() == 0;
502         }
503     }
504 }