blob: ae91f111898137b3f0b8b950390e65b772b94503 [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
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.browser;
18
19import com.android.browser.IntentHandler.UrlData;
20import com.android.browser.search.SearchEngine;
21import com.android.common.Search;
22
23import android.app.Activity;
24import android.app.DownloadManager;
25import android.app.SearchManager;
26import android.content.ClipboardManager;
27import android.content.ContentProvider;
28import android.content.ContentProviderClient;
29import android.content.ContentResolver;
30import android.content.ContentValues;
31import android.content.Context;
32import android.content.Intent;
33import android.content.pm.PackageManager;
34import android.content.pm.ResolveInfo;
35import android.content.res.Configuration;
Leon Scroggins1961ed22010-12-07 15:22:21 -050036import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070037import android.database.Cursor;
38import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070039import android.graphics.Bitmap;
40import android.graphics.Canvas;
41import android.graphics.Picture;
42import android.net.Uri;
43import android.net.http.SslError;
44import android.os.AsyncTask;
45import android.os.Bundle;
Leon Scrogginsac993842011-02-02 12:54:07 -050046import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070047import android.os.Handler;
48import android.os.Message;
49import android.os.PowerManager;
50import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000051import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070052import android.provider.Browser;
53import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070054import android.provider.BrowserContract.Images;
55import android.provider.ContactsContract;
56import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080057import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070058import android.speech.RecognizerResultsIntent;
59import android.text.TextUtils;
60import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080061import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070062import android.view.ActionMode;
63import android.view.ContextMenu;
64import android.view.ContextMenu.ContextMenuInfo;
65import android.view.Gravity;
66import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070067import android.view.Menu;
68import android.view.MenuInflater;
69import android.view.MenuItem;
70import android.view.MenuItem.OnMenuItemClickListener;
71import android.view.View;
72import android.webkit.CookieManager;
73import android.webkit.CookieSyncManager;
74import android.webkit.HttpAuthHandler;
75import android.webkit.SslErrorHandler;
76import android.webkit.ValueCallback;
77import android.webkit.WebChromeClient;
78import android.webkit.WebIconDatabase;
79import android.webkit.WebSettings;
80import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050081import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070082
83import java.io.ByteArrayOutputStream;
84import java.io.File;
85import java.net.URLEncoder;
86import java.util.Calendar;
87import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080088import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070089
90/**
91 * Controller for browser
92 */
93public class Controller
94 implements WebViewController, UiController {
95
96 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -080097 private static final String SEND_APP_ID_EXTRA =
98 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
99
Michael Kolb8233fac2010-10-26 16:08:53 -0700100
101 // public message ids
102 public final static int LOAD_URL = 1001;
103 public final static int STOP_LOAD = 1002;
104
105 // Message Ids
106 private static final int FOCUS_NODE_HREF = 102;
107 private static final int RELEASE_WAKELOCK = 107;
108
109 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
110
111 private static final int OPEN_BOOKMARKS = 201;
112
113 private static final int EMPTY_MENU = -1;
114
Michael Kolb8233fac2010-10-26 16:08:53 -0700115 // activity requestCode
116 final static int PREFERENCES_PAGE = 3;
117 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000118 final static int AUTOFILL_SETUP = 5;
119
Michael Kolb8233fac2010-10-26 16:08:53 -0700120 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
121
122 // As the ids are dynamically created, we can't guarantee that they will
123 // be in sequence, so this static array maps ids to a window number.
124 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
125 { R.id.window_one_menu_id, R.id.window_two_menu_id,
126 R.id.window_three_menu_id, R.id.window_four_menu_id,
127 R.id.window_five_menu_id, R.id.window_six_menu_id,
128 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
129
130 // "source" parameter for Google search through search key
131 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
132 // "source" parameter for Google search through simplily type
133 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
134
135 private Activity mActivity;
136 private UI mUi;
137 private TabControl mTabControl;
138 private BrowserSettings mSettings;
139 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800140 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700141
142 private WakeLock mWakeLock;
143
144 private UrlHandler mUrlHandler;
145 private UploadHandler mUploadHandler;
146 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700147 private PageDialogsHandler mPageDialogsHandler;
148 private NetworkStateHandler mNetworkHandler;
149
Ben Murdoch8029a772010-11-16 11:58:21 +0000150 private Message mAutoFillSetupMessage;
151
Michael Kolb8233fac2010-10-26 16:08:53 -0700152 private boolean mShouldShowErrorConsole;
153
154 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
155
156 // FIXME, temp address onPrepareMenu performance problem.
157 // When we move everything out of view, we should rewrite this.
158 private int mCurrentMenuState = 0;
159 private int mMenuState = R.id.MAIN_MENU;
160 private int mOldMenuState = EMPTY_MENU;
161 private Menu mCachedMenu;
162
163 // Used to prevent chording to result in firing two shortcuts immediately
164 // one after another. Fixes bug 1211714.
165 boolean mCanChord;
166 private boolean mMenuIsDown;
167
168 // For select and find, we keep track of the ActionMode so that
169 // finish() can be called as desired.
170 private ActionMode mActionMode;
171
172 /**
173 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
174 * of whether the configuration has changed. The first onMenuOpened call
175 * after a configuration change is simply a reopening of the same menu
176 * (i.e. mIconView did not change).
177 */
178 private boolean mConfigChanged;
179
180 /**
181 * Keeps track of whether the options menu is open. This is important in
182 * determining whether to show or hide the title bar overlay
183 */
184 private boolean mOptionsMenuOpen;
185
186 /**
187 * Whether or not the options menu is in its bigger, popup menu form. When
188 * true, we want the title bar overlay to be gone. When false, we do not.
189 * Only meaningful if mOptionsMenuOpen is true.
190 */
191 private boolean mExtendedMenuOpen;
192
193 private boolean mInLoad;
194
195 private boolean mActivityPaused = true;
196 private boolean mLoadStopped;
197
198 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500199 // Checks to see when the bookmarks database has changed, and updates the
200 // Tabs' notion of whether they represent bookmarked sites.
201 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800202 private DataController mDataController;
Michael Kolb8233fac2010-10-26 16:08:53 -0700203
204 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
205 @Override
206 public Void doInBackground(File... files) {
207 if (files != null) {
208 for (File f : files) {
209 if (!f.delete()) {
210 Log.e(LOGTAG, f.getPath() + " was not deleted");
211 }
212 }
213 }
214 return null;
215 }
216 }
217
218 public Controller(Activity browser) {
219 mActivity = browser;
220 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800221 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700222 mTabControl = new TabControl(this);
223 mSettings.setController(this);
224
225 mUrlHandler = new UrlHandler(this);
226 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700227 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
228
229 PowerManager pm = (PowerManager) mActivity
230 .getSystemService(Context.POWER_SERVICE);
231 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
232
233 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500234 mBookmarksObserver = new ContentObserver(mHandler) {
235 @Override
236 public void onChange(boolean selfChange) {
237 int size = mTabControl.getTabCount();
238 for (int i = 0; i < size; i++) {
239 mTabControl.getTab(i).updateBookmarkedStatus();
240 }
241 }
242
243 };
244 browser.getContentResolver().registerContentObserver(
245 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700246
247 mNetworkHandler = new NetworkStateHandler(mActivity, this);
248 // Start watching the default geolocation permissions
249 mSystemAllowGeolocationOrigins =
250 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
251 mSystemAllowGeolocationOrigins.start();
252
253 retainIconsOnStartup();
254 }
255
Patrick Scott7d50a932011-02-04 09:27:26 -0500256 void start(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700257 // Unless the last browser usage was within 24 hours, destroy any
258 // remaining incognito tabs.
259
260 Calendar lastActiveDate = icicle != null ?
261 (Calendar) icicle.getSerializable("lastActiveDate") : null;
262 Calendar today = Calendar.getInstance();
263 Calendar yesterday = Calendar.getInstance();
264 yesterday.add(Calendar.DATE, -1);
265
Patrick Scott7d50a932011-02-04 09:27:26 -0500266 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700267 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800268 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700269
Patrick Scott7d50a932011-02-04 09:27:26 -0500270 // Find out if we will restore any state and remember the tab.
271 final int currentTab =
272 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000273
Patrick Scott7d50a932011-02-04 09:27:26 -0500274 if (currentTab == -1) {
275 // Not able to restore so we go ahead and clear session cookies. We
276 // must do this before trying to login the user as we don't want to
277 // clear any session cookies set during login.
278 CookieManager.getInstance().removeSessionCookie();
279 }
280
281 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings,
282 new Runnable() {
283 @Override public void run() {
284 start(icicle, intent, currentTab, restoreIncognitoTabs);
285 }
286 });
287 }
288
289 private void start(Bundle icicle, Intent intent, int currentTab,
290 boolean restoreIncognitoTabs) {
291 if (currentTab == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700292 final Bundle extra = intent.getExtras();
293 // Create an initial tab.
294 // If the intent is ACTION_VIEW and data is not null, the Browser is
295 // invoked to view the content by another application. In this case,
296 // the tab will be close when exit.
297 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
298
299 String action = intent.getAction();
300 final Tab t = mTabControl.createNewTab(
301 (Intent.ACTION_VIEW.equals(action) &&
302 intent.getData() != null)
303 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
304 .equals(action),
305 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
306 urlData.mUrl, false);
307 addTab(t);
308 setActiveTab(t);
309 WebView webView = t.getWebView();
310 if (extra != null) {
311 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
312 if (scale > 0 && scale <= 1000) {
313 webView.setInitialScale(scale);
314 }
315 }
316
317 if (urlData.isEmpty()) {
318 loadUrl(webView, mSettings.getHomePage());
319 } else {
Michael Kolbcd424e92011-02-24 10:26:26 -0800320 // monkey protection against delayed start
321 if (t != null) {
322 loadUrlDataIn(t, urlData);
323 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700324 }
325 } else {
Patrick Scott7d50a932011-02-04 09:27:26 -0500326 mTabControl.restoreState(icicle, currentTab, restoreIncognitoTabs,
327 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800328 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700329 // TabControl.restoreState() will create a new tab even if
330 // restoring the state fails.
331 setActiveTab(mTabControl.getCurrentTab());
332 }
333 // clear up the thumbnail directory, which is no longer used;
334 // ideally this should only be run once after an upgrade from
335 // a previous version of the browser
336 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
337 .listFiles());
338 // Read JavaScript flags if it exists.
339 String jsFlags = getSettings().getJsFlags();
340 if (jsFlags.trim().length() != 0) {
341 getCurrentWebView().setJsFlags(jsFlags);
342 }
John Reck439c9a52010-12-14 10:04:39 -0800343 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
344 bookmarksOrHistoryPicker(false);
345 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700346 }
347
348 void setWebViewFactory(WebViewFactory factory) {
349 mFactory = factory;
350 }
351
Michael Kolb1514bb72010-11-22 09:11:48 -0800352 @Override
353 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700354 return mFactory;
355 }
356
357 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800358 public void onSetWebView(Tab tab, WebView view) {
359 mUi.onSetWebView(tab, view);
360 }
361
362 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800363 public void createSubWindow(Tab tab) {
364 endActionMode();
365 WebView mainView = tab.getWebView();
366 WebView subView = mFactory.createWebView((mainView == null)
367 ? false
368 : mainView.isPrivateBrowsingEnabled());
369 mUi.createSubWindow(tab, subView);
370 }
371
372 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700373 public Activity getActivity() {
374 return mActivity;
375 }
376
377 void setUi(UI ui) {
378 mUi = ui;
379 }
380
381 BrowserSettings getSettings() {
382 return mSettings;
383 }
384
385 IntentHandler getIntentHandler() {
386 return mIntentHandler;
387 }
388
389 @Override
390 public UI getUi() {
391 return mUi;
392 }
393
394 int getMaxTabs() {
395 return mActivity.getResources().getInteger(R.integer.max_tabs);
396 }
397
398 @Override
399 public TabControl getTabControl() {
400 return mTabControl;
401 }
402
Michael Kolb1bf23132010-11-19 12:55:12 -0800403 @Override
404 public List<Tab> getTabs() {
405 return mTabControl.getTabs();
406 }
407
Michael Kolb8233fac2010-10-26 16:08:53 -0700408 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000409 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700410 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000411 // WebIconDatabase needs to be retrieved on the UI thread so that if
412 // it has not been created successfully yet the Handler is started on the
413 // UI thread.
414 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
415 }
416
417 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
418 private WebIconDatabase mDb;
419
420 public RetainIconsOnStartupTask(WebIconDatabase db) {
421 mDb = db;
422 }
423
John Recka00cbbd2010-12-16 12:38:19 -0800424 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000425 protected Void doInBackground(Void... unused) {
426 mDb.open(mActivity.getDir("icons", 0).getPath());
427 Cursor c = null;
428 try {
429 c = Browser.getAllBookmarks(mActivity.getContentResolver());
430 if (c.moveToFirst()) {
431 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
432 do {
433 String url = c.getString(urlIndex);
434 mDb.retainIconForPageUrl(url);
435 } while (c.moveToNext());
436 }
437 } catch (IllegalStateException e) {
438 Log.e(LOGTAG, "retainIconsOnStartup", e);
439 } finally {
440 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700441 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000442
443 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700444 }
445 }
446
447 private void startHandler() {
448 mHandler = new Handler() {
449
450 @Override
451 public void handleMessage(Message msg) {
452 switch (msg.what) {
453 case OPEN_BOOKMARKS:
454 bookmarksOrHistoryPicker(false);
455 break;
456 case FOCUS_NODE_HREF:
457 {
458 String url = (String) msg.getData().get("url");
459 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500460 String src = (String) msg.getData().get("src");
461 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700462 if (TextUtils.isEmpty(url)) {
463 break;
464 }
465 HashMap focusNodeMap = (HashMap) msg.obj;
466 WebView view = (WebView) focusNodeMap.get("webview");
467 // Only apply the action if the top window did not change.
468 if (getCurrentTopWebView() != view) {
469 break;
470 }
471 switch (msg.arg1) {
472 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700473 loadUrlFromContext(getCurrentTopWebView(), url);
474 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500475 case R.id.view_image_context_menu_id:
476 loadUrlFromContext(getCurrentTopWebView(), src);
477 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500478 case R.id.open_newtab_context_menu_id:
479 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800480 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500481 if (newTab != null && newTab != parent) {
482 parent.addChildTab(newTab);
483 }
484 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700485 case R.id.copy_link_context_menu_id:
486 copy(url);
487 break;
488 case R.id.save_link_context_menu_id:
489 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500490 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000491 mActivity, url, null, null, null,
492 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700493 break;
494 }
495 break;
496 }
497
498 case LOAD_URL:
499 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
500 break;
501
502 case STOP_LOAD:
503 stopLoading();
504 break;
505
506 case RELEASE_WAKELOCK:
507 if (mWakeLock.isHeld()) {
508 mWakeLock.release();
509 // if we reach here, Browser should be still in the
510 // background loading after WAKELOCK_TIMEOUT (5-min).
511 // To avoid burning the battery, stop loading.
512 mTabControl.stopAllLoading();
513 }
514 break;
515
516 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800517 Tab tab = (Tab) msg.obj;
518 if (tab != null) {
519 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700520 }
521 break;
522 }
523 }
524 };
525
526 }
527
Michael Kolbba99c5d2010-11-29 14:57:41 -0800528 @Override
529 public void shareCurrentPage() {
530 shareCurrentPage(mTabControl.getCurrentTab());
531 }
532
533 private void shareCurrentPage(Tab tab) {
534 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800535 sharePage(mActivity, tab.getTitle(),
536 tab.getUrl(), tab.getFavicon(),
537 createScreenshot(tab.getWebView(),
538 getDesiredThumbnailWidth(mActivity),
539 getDesiredThumbnailHeight(mActivity)));
540 }
541 }
542
Michael Kolb8233fac2010-10-26 16:08:53 -0700543 /**
544 * Share a page, providing the title, url, favicon, and a screenshot. Uses
545 * an {@link Intent} to launch the Activity chooser.
546 * @param c Context used to launch a new Activity.
547 * @param title Title of the page. Stored in the Intent with
548 * {@link Intent#EXTRA_SUBJECT}
549 * @param url URL of the page. Stored in the Intent with
550 * {@link Intent#EXTRA_TEXT}
551 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
552 * with {@link Browser#EXTRA_SHARE_FAVICON}
553 * @param screenshot Bitmap of a screenshot of the page. Stored in the
554 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
555 */
556 static final void sharePage(Context c, String title, String url,
557 Bitmap favicon, Bitmap screenshot) {
558 Intent send = new Intent(Intent.ACTION_SEND);
559 send.setType("text/plain");
560 send.putExtra(Intent.EXTRA_TEXT, url);
561 send.putExtra(Intent.EXTRA_SUBJECT, title);
562 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
563 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
564 try {
565 c.startActivity(Intent.createChooser(send, c.getString(
566 R.string.choosertitle_sharevia)));
567 } catch(android.content.ActivityNotFoundException ex) {
568 // if no app handles it, do nothing
569 }
570 }
571
572 private void copy(CharSequence text) {
573 ClipboardManager cm = (ClipboardManager) mActivity
574 .getSystemService(Context.CLIPBOARD_SERVICE);
575 cm.setText(text);
576 }
577
578 // lifecycle
579
580 protected void onConfgurationChanged(Configuration config) {
581 mConfigChanged = true;
582 if (mPageDialogsHandler != null) {
583 mPageDialogsHandler.onConfigurationChanged(config);
584 }
585 mUi.onConfigurationChanged(config);
586 }
587
588 @Override
589 public void handleNewIntent(Intent intent) {
590 mIntentHandler.onNewIntent(intent);
591 }
592
593 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800594 if (mUi.isCustomViewShowing()) {
595 hideCustomView();
596 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700597 if (mActivityPaused) {
598 Log.e(LOGTAG, "BrowserActivity is already paused.");
599 return;
600 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700601 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800602 Tab tab = mTabControl.getCurrentTab();
603 if (tab != null) {
604 tab.pause();
605 if (!pauseWebViewTimers(tab)) {
606 mWakeLock.acquire();
607 mHandler.sendMessageDelayed(mHandler
608 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
609 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700610 }
611 mUi.onPause();
612 mNetworkHandler.onPause();
613
614 WebView.disablePlatformNotifications();
615 }
616
617 void onSaveInstanceState(Bundle outState) {
618 // the default implementation requires each view to have an id. As the
619 // browser handles the state itself and it doesn't use id for the views,
620 // don't call the default implementation. Otherwise it will trigger the
621 // warning like this, "couldn't save which view has focus because the
622 // focused view XXX has no id".
623
624 // Save all the tabs
625 mTabControl.saveState(outState);
626 // Save time so that we know how old incognito tabs (if any) are.
627 outState.putSerializable("lastActiveDate", Calendar.getInstance());
628 }
629
630 void onResume() {
631 if (!mActivityPaused) {
632 Log.e(LOGTAG, "BrowserActivity is already resumed.");
633 return;
634 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700635 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800636 Tab current = mTabControl.getCurrentTab();
637 if (current != null) {
638 current.resume();
639 resumeWebViewTimers(current);
640 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700641 if (mWakeLock.isHeld()) {
642 mHandler.removeMessages(RELEASE_WAKELOCK);
643 mWakeLock.release();
644 }
645 mUi.onResume();
646 mNetworkHandler.onResume();
647 WebView.enablePlatformNotifications();
648 }
649
Michael Kolb70976932010-11-30 11:34:01 -0800650 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800651 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800652 * @param tab guaranteed non-null
653 */
654 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700655 boolean inLoad = tab.inPageLoad();
656 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
657 CookieSyncManager.getInstance().startSync();
658 WebView w = tab.getWebView();
659 if (w != null) {
660 w.resumeTimers();
661 }
662 }
663 }
664
Michael Kolb70976932010-11-30 11:34:01 -0800665 /**
666 * Pause all WebView timers using the WebView of the given tab
667 * @param tab
668 * @return true if the timers are paused or tab is null
669 */
670 private boolean pauseWebViewTimers(Tab tab) {
671 if (tab == null) {
672 return true;
673 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700674 CookieSyncManager.getInstance().stopSync();
675 WebView w = getCurrentWebView();
676 if (w != null) {
677 w.pauseTimers();
678 }
679 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700680 }
Michael Kolb70976932010-11-30 11:34:01 -0800681 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700682 }
683
684 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800685 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700686 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
687 mUploadHandler = null;
688 }
689 if (mTabControl == null) return;
690 mUi.onDestroy();
691 // Remove the current tab and sub window
692 Tab t = mTabControl.getCurrentTab();
693 if (t != null) {
694 dismissSubWindow(t);
695 removeTab(t);
696 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500697 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700698 // Destroy all the tabs
699 mTabControl.destroy();
700 WebIconDatabase.getInstance().close();
701 // Stop watching the default geolocation permissions
702 mSystemAllowGeolocationOrigins.stop();
703 mSystemAllowGeolocationOrigins = null;
704 }
705
706 protected boolean isActivityPaused() {
707 return mActivityPaused;
708 }
709
710 protected void onLowMemory() {
711 mTabControl.freeMemory();
712 }
713
714 @Override
715 public boolean shouldShowErrorConsole() {
716 return mShouldShowErrorConsole;
717 }
718
719 protected void setShouldShowErrorConsole(boolean show) {
720 if (show == mShouldShowErrorConsole) {
721 // Nothing to do.
722 return;
723 }
724 mShouldShowErrorConsole = show;
725 Tab t = mTabControl.getCurrentTab();
726 if (t == null) {
727 // There is no current tab so we cannot toggle the error console
728 return;
729 }
730 mUi.setShouldShowErrorConsole(t, show);
731 }
732
733 @Override
734 public void stopLoading() {
735 mLoadStopped = true;
736 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700737 WebView w = getCurrentTopWebView();
738 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700739 mUi.onPageStopped(tab);
740 }
741
742 boolean didUserStopLoading() {
743 return mLoadStopped;
744 }
745
746 // WebViewController
747
748 @Override
John Reck324d4402011-01-11 16:56:42 -0800749 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700750
751 // We've started to load a new page. If there was a pending message
752 // to save a screenshot then we will now take the new page and save
753 // an incorrect screenshot. Therefore, remove any pending thumbnail
754 // messages from the queue.
755 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800756 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700757
758 // reset sync timer to avoid sync starts during loading a page
759 CookieSyncManager.getInstance().resetSync();
760
761 if (!mNetworkHandler.isNetworkUp()) {
762 view.setNetworkAvailable(false);
763 }
764
765 // when BrowserActivity just starts, onPageStarted may be called before
766 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
767 // to start the timer. As we won't switch tabs while an activity is in
768 // pause state, we can ensure calling resume and pause in pair.
769 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800770 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700771 }
772 mLoadStopped = false;
773 if (!mNetworkHandler.isNetworkUp()) {
774 mNetworkHandler.createAndShowNetworkDialog();
775 }
776 endActionMode();
777
John Reck30c714c2010-12-16 17:30:34 -0800778 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700779
John Reck324d4402011-01-11 16:56:42 -0800780 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700781 // update the bookmark database for favicon
782 maybeUpdateFavicon(tab, null, url, favicon);
783
784 Performance.tracePageStart(url);
785
786 // Performance probe
787 if (false) {
788 Performance.onPageStarted();
789 }
790
791 }
792
793 @Override
John Reck324d4402011-01-11 16:56:42 -0800794 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800795 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800796 if (!tab.isPrivateBrowsingEnabled()
797 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700798 if (tab.inForeground() && !didUserStopLoading()
799 || !tab.inForeground()) {
800 // Only update the bookmark screenshot if the user did not
801 // cancel the load early.
802 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800803 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700804 500);
805 }
806 }
807 // pause the WebView timer and release the wake lock if it is finished
808 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800809 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700810 if (mWakeLock.isHeld()) {
811 mHandler.removeMessages(RELEASE_WAKELOCK);
812 mWakeLock.release();
813 }
814 }
815 // Performance probe
816 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800817 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700818 }
819
820 Performance.tracePageFinished();
821 }
822
823 @Override
John Reck30c714c2010-12-16 17:30:34 -0800824 public void onProgressChanged(Tab tab) {
825 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700826
827 if (newProgress == 100) {
828 CookieSyncManager.getInstance().sync();
829 // onProgressChanged() may continue to be called after the main
830 // frame has finished loading, as any remaining sub frames continue
831 // to load. We'll only get called once though with newProgress as
832 // 100 when everything is loaded. (onPageFinished is called once
833 // when the main frame completes loading regardless of the state of
834 // any sub frames so calls to onProgressChanges may continue after
835 // onPageFinished has executed)
836 if (mInLoad) {
837 mInLoad = false;
838 updateInLoadMenuItems(mCachedMenu);
839 }
840 } else {
841 if (!mInLoad) {
842 // onPageFinished may have already been called but a subframe is
843 // still loading and updating the progress. Reset mInLoad and
844 // update the menu items.
845 mInLoad = true;
846 updateInLoadMenuItems(mCachedMenu);
847 }
848 }
John Reck30c714c2010-12-16 17:30:34 -0800849 mUi.onProgressChanged(tab);
850 }
851
852 @Override
853 public void onUpdatedLockIcon(Tab tab) {
854 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700855 }
856
857 @Override
858 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800859 mUi.onTabDataChanged(tab);
860 final String pageUrl = tab.getUrl();
John Reck324d4402011-01-11 16:56:42 -0800861 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700862 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
863 return;
864 }
865 // Update the title in the history database if not in private browsing mode
866 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800867 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700868 }
869 }
870
871 @Override
872 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800873 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700874 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
875 }
876
877 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800878 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
879 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700880 }
881
882 @Override
883 public boolean shouldOverrideKeyEvent(KeyEvent event) {
884 if (mMenuIsDown) {
885 // only check shortcut key when MENU is held
886 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
887 event);
888 } else {
889 return false;
890 }
891 }
892
893 @Override
894 public void onUnhandledKeyEvent(KeyEvent event) {
895 if (!isActivityPaused()) {
896 if (event.getAction() == KeyEvent.ACTION_DOWN) {
897 mActivity.onKeyDown(event.getKeyCode(), event);
898 } else {
899 mActivity.onKeyUp(event.getKeyCode(), event);
900 }
901 }
902 }
903
904 @Override
John Reck324d4402011-01-11 16:56:42 -0800905 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700906 // Don't save anything in private browsing mode
907 if (tab.isPrivateBrowsingEnabled()) return;
John Reck324d4402011-01-11 16:56:42 -0800908 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700909
John Reck324d4402011-01-11 16:56:42 -0800910 if (TextUtils.isEmpty(url)
911 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700912 return;
913 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800914 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700915 WebIconDatabase.getInstance().retainIconForPageUrl(url);
916 }
917
918 @Override
919 public void getVisitedHistory(final ValueCallback<String[]> callback) {
920 AsyncTask<Void, Void, String[]> task =
921 new AsyncTask<Void, Void, String[]>() {
922 @Override
923 public String[] doInBackground(Void... unused) {
924 return Browser.getVisitedHistory(mActivity.getContentResolver());
925 }
926 @Override
927 public void onPostExecute(String[] result) {
928 callback.onReceiveValue(result);
929 }
930 };
931 task.execute();
932 }
933
934 @Override
935 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
936 final HttpAuthHandler handler, final String host,
937 final String realm) {
938 String username = null;
939 String password = null;
940
941 boolean reuseHttpAuthUsernamePassword
942 = handler.useHttpAuthUsernamePassword();
943
944 if (reuseHttpAuthUsernamePassword && view != null) {
945 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
946 if (credentials != null && credentials.length == 2) {
947 username = credentials[0];
948 password = credentials[1];
949 }
950 }
951
952 if (username != null && password != null) {
953 handler.proceed(username, password);
954 } else {
955 if (tab.inForeground()) {
956 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
957 } else {
958 handler.cancel();
959 }
960 }
961 }
962
963 @Override
964 public void onDownloadStart(Tab tab, String url, String userAgent,
965 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000966 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500967 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000968 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
969 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700970 // This Tab was opened for the sole purpose of downloading a
971 // file. Remove it.
972 if (tab == mTabControl.getCurrentTab()) {
973 // In this case, the Tab is still on top.
974 goBackOnePageOrQuit();
975 } else {
976 // In this case, it is not.
977 closeTab(tab);
978 }
979 }
980 }
981
982 @Override
983 public Bitmap getDefaultVideoPoster() {
984 return mUi.getDefaultVideoPoster();
985 }
986
987 @Override
988 public View getVideoLoadingProgressView() {
989 return mUi.getVideoLoadingProgressView();
990 }
991
992 @Override
993 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
994 SslError error) {
995 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
996 }
997
998 // helper method
999
1000 /*
1001 * Update the favorites icon if the private browsing isn't enabled and the
1002 * icon is valid.
1003 */
1004 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1005 final String url, Bitmap favicon) {
1006 if (favicon == null) {
1007 return;
1008 }
1009 if (!tab.isPrivateBrowsingEnabled()) {
1010 Bookmarks.updateFavicon(mActivity
1011 .getContentResolver(), originalUrl, url, favicon);
1012 }
1013 }
1014
Leon Scroggins4cd97792010-12-03 15:31:56 -05001015 @Override
1016 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001017 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001018 mUi.bookmarkedStatusHasChanged(tab);
1019 }
1020
Michael Kolb8233fac2010-10-26 16:08:53 -07001021 // end WebViewController
1022
1023 protected void pageUp() {
1024 getCurrentTopWebView().pageUp(false);
1025 }
1026
1027 protected void pageDown() {
1028 getCurrentTopWebView().pageDown(false);
1029 }
1030
1031 // callback from phone title bar
1032 public void editUrl() {
1033 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001034 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001035 }
1036
Michael Kolbcfa3af52010-12-14 10:36:11 -08001037 public void startVoiceSearch() {
1038 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1039 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1040 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1041 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1042 mActivity.getComponentName().flattenToString());
1043 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001044 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001045 mActivity.startActivity(intent);
1046 }
1047
Michael Kolb8233fac2010-10-26 16:08:53 -07001048 public void activateVoiceSearchMode(String title) {
1049 mUi.showVoiceTitleBar(title);
1050 }
1051
1052 public void revertVoiceSearchMode(Tab tab) {
1053 mUi.revertVoiceTitleBar(tab);
1054 }
1055
1056 public void showCustomView(Tab tab, View view,
1057 WebChromeClient.CustomViewCallback callback) {
1058 if (tab.inForeground()) {
1059 if (mUi.isCustomViewShowing()) {
1060 callback.onCustomViewHidden();
1061 return;
1062 }
1063 mUi.showCustomView(view, callback);
1064 // Save the menu state and set it to empty while the custom
1065 // view is showing.
1066 mOldMenuState = mMenuState;
1067 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001068 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001069 }
1070 }
1071
1072 @Override
1073 public void hideCustomView() {
1074 if (mUi.isCustomViewShowing()) {
1075 mUi.onHideCustomView();
1076 // Reset the old menu state.
1077 mMenuState = mOldMenuState;
1078 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001079 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001080 }
1081 }
1082
1083 protected void onActivityResult(int requestCode, int resultCode,
1084 Intent intent) {
1085 if (getCurrentTopWebView() == null) return;
1086 switch (requestCode) {
1087 case PREFERENCES_PAGE:
1088 if (resultCode == Activity.RESULT_OK && intent != null) {
1089 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1090 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1091 mTabControl.removeParentChildRelationShips();
1092 }
1093 }
1094 break;
1095 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001096 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001097 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001098 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001099 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001100 case AUTOFILL_SETUP:
1101 // Determine whether a profile was actually set up or not
1102 // and if so, send the message back to the WebTextView to
1103 // fill the form with the new profile.
1104 if (getSettings().getAutoFillProfile() != null) {
1105 mAutoFillSetupMessage.sendToTarget();
1106 mAutoFillSetupMessage = null;
1107 }
1108 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001109 default:
1110 break;
1111 }
1112 getCurrentTopWebView().requestFocus();
1113 }
1114
1115 /**
1116 * Open the Go page.
1117 * @param startWithHistory If true, open starting on the history tab.
1118 * Otherwise, start with the bookmarks tab.
1119 */
1120 @Override
1121 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1122 if (mTabControl.getCurrentWebView() == null) {
1123 return;
1124 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001125 // clear action mode
1126 if (isInCustomActionMode()) {
1127 endActionMode();
1128 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001129 Bundle extras = new Bundle();
1130 // Disable opening in a new window if we have maxed out the windows
1131 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1132 !mTabControl.canCreateNewTab());
1133 mUi.showComboView(startWithHistory, extras);
1134 }
1135
1136 // combo view callbacks
1137
1138 /**
1139 * callback from ComboPage when clear history is requested
1140 */
1141 public void onRemoveParentChildRelationships() {
1142 mTabControl.removeParentChildRelationShips();
1143 }
1144
1145 /**
1146 * callback from ComboPage when bookmark/history selection
1147 */
1148 @Override
1149 public void onUrlSelected(String url, boolean newTab) {
1150 removeComboView();
1151 if (!TextUtils.isEmpty(url)) {
1152 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001153 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001154 } else {
1155 final Tab currentTab = mTabControl.getCurrentTab();
1156 dismissSubWindow(currentTab);
1157 loadUrl(getCurrentTopWebView(), url);
1158 }
1159 }
1160 }
1161
1162 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001163 * dismiss the ComboPage
1164 */
1165 @Override
1166 public void removeComboView() {
1167 mUi.hideComboView();
1168 }
1169
1170 // active tabs page handling
1171
1172 protected void showActiveTabsPage() {
1173 mMenuState = EMPTY_MENU;
1174 mUi.showActiveTabsPage();
1175 }
1176
1177 /**
1178 * Remove the active tabs page.
1179 * @param needToAttach If true, the active tabs page did not attach a tab
1180 * to the content view, so we need to do that here.
1181 */
1182 @Override
1183 public void removeActiveTabsPage(boolean needToAttach) {
1184 mMenuState = R.id.MAIN_MENU;
1185 mUi.removeActiveTabsPage();
1186 if (needToAttach) {
1187 setActiveTab(mTabControl.getCurrentTab());
1188 }
1189 getCurrentTopWebView().requestFocus();
1190 }
1191
1192 // key handling
1193 protected void onBackKey() {
1194 if (!mUi.onBackKey()) {
1195 WebView subwindow = mTabControl.getCurrentSubWindow();
1196 if (subwindow != null) {
1197 if (subwindow.canGoBack()) {
1198 subwindow.goBack();
1199 } else {
1200 dismissSubWindow(mTabControl.getCurrentTab());
1201 }
1202 } else {
1203 goBackOnePageOrQuit();
1204 }
1205 }
1206 }
1207
1208 // menu handling and state
1209 // TODO: maybe put into separate handler
1210
1211 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001212 if (mOptionsMenuHandler != null) {
1213 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1214 }
1215
John Reckd73c5a22010-12-22 10:22:50 -08001216 if (mMenuState == EMPTY_MENU) {
1217 return false;
1218 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001219 MenuInflater inflater = mActivity.getMenuInflater();
1220 inflater.inflate(R.menu.browser, menu);
1221 updateInLoadMenuItems(menu);
1222 // hold on to the menu reference here; it is used by the page callbacks
1223 // to update the menu based on loading state
1224 mCachedMenu = menu;
1225 return true;
1226 }
1227
1228 protected void onCreateContextMenu(ContextMenu menu, View v,
1229 ContextMenuInfo menuInfo) {
1230 if (v instanceof TitleBarBase) {
1231 return;
1232 }
1233 if (!(v instanceof WebView)) {
1234 return;
1235 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001236 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001237 WebView.HitTestResult result = webview.getHitTestResult();
1238 if (result == null) {
1239 return;
1240 }
1241
1242 int type = result.getType();
1243 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1244 Log.w(LOGTAG,
1245 "We should not show context menu when nothing is touched");
1246 return;
1247 }
1248 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1249 // let TextView handles context menu
1250 return;
1251 }
1252
1253 // Note, http://b/issue?id=1106666 is requesting that
1254 // an inflated menu can be used again. This is not available
1255 // yet, so inflate each time (yuk!)
1256 MenuInflater inflater = mActivity.getMenuInflater();
1257 inflater.inflate(R.menu.browsercontext, menu);
1258
1259 // Show the correct menu group
1260 final String extra = result.getExtra();
1261 menu.setGroupVisible(R.id.PHONE_MENU,
1262 type == WebView.HitTestResult.PHONE_TYPE);
1263 menu.setGroupVisible(R.id.EMAIL_MENU,
1264 type == WebView.HitTestResult.EMAIL_TYPE);
1265 menu.setGroupVisible(R.id.GEO_MENU,
1266 type == WebView.HitTestResult.GEO_TYPE);
1267 menu.setGroupVisible(R.id.IMAGE_MENU,
1268 type == WebView.HitTestResult.IMAGE_TYPE
1269 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1270 menu.setGroupVisible(R.id.ANCHOR_MENU,
1271 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1272 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001273 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1274 || type == WebView.HitTestResult.PHONE_TYPE
1275 || type == WebView.HitTestResult.EMAIL_TYPE
1276 || type == WebView.HitTestResult.GEO_TYPE;
1277 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1278 if (hitText) {
1279 menu.findItem(R.id.select_text_menu_id)
1280 .setOnMenuItemClickListener(new SelectText(webview));
1281 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001282 // Setup custom handling depending on the type
1283 switch (type) {
1284 case WebView.HitTestResult.PHONE_TYPE:
1285 menu.setHeaderTitle(Uri.decode(extra));
1286 menu.findItem(R.id.dial_context_menu_id).setIntent(
1287 new Intent(Intent.ACTION_VIEW, Uri
1288 .parse(WebView.SCHEME_TEL + extra)));
1289 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1290 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1291 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1292 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1293 addIntent);
1294 menu.findItem(R.id.copy_phone_context_menu_id)
1295 .setOnMenuItemClickListener(
1296 new Copy(extra));
1297 break;
1298
1299 case WebView.HitTestResult.EMAIL_TYPE:
1300 menu.setHeaderTitle(extra);
1301 menu.findItem(R.id.email_context_menu_id).setIntent(
1302 new Intent(Intent.ACTION_VIEW, Uri
1303 .parse(WebView.SCHEME_MAILTO + extra)));
1304 menu.findItem(R.id.copy_mail_context_menu_id)
1305 .setOnMenuItemClickListener(
1306 new Copy(extra));
1307 break;
1308
1309 case WebView.HitTestResult.GEO_TYPE:
1310 menu.setHeaderTitle(extra);
1311 menu.findItem(R.id.map_context_menu_id).setIntent(
1312 new Intent(Intent.ACTION_VIEW, Uri
1313 .parse(WebView.SCHEME_GEO
1314 + URLEncoder.encode(extra))));
1315 menu.findItem(R.id.copy_geo_context_menu_id)
1316 .setOnMenuItemClickListener(
1317 new Copy(extra));
1318 break;
1319
1320 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1321 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001322 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001323 // decide whether to show the open link in new tab option
1324 boolean showNewTab = mTabControl.canCreateNewTab();
1325 MenuItem newTabItem
1326 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001327 newTabItem.setTitle(
1328 BrowserSettings.getInstance().openInBackground()
1329 ? R.string.contextmenu_openlink_newwindow_background
1330 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001331 newTabItem.setVisible(showNewTab);
1332 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001333 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1334 newTabItem.setOnMenuItemClickListener(
1335 new MenuItem.OnMenuItemClickListener() {
1336 @Override
1337 public boolean onMenuItemClick(MenuItem item) {
1338 final HashMap<String, WebView> hrefMap =
1339 new HashMap<String, WebView>();
1340 hrefMap.put("webview", webview);
1341 final Message msg = mHandler.obtainMessage(
1342 FOCUS_NODE_HREF,
1343 R.id.open_newtab_context_menu_id,
1344 0, hrefMap);
1345 webview.requestFocusNodeHref(msg);
1346 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001347 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001348 });
1349 } else {
1350 newTabItem.setOnMenuItemClickListener(
1351 new MenuItem.OnMenuItemClickListener() {
1352 @Override
1353 public boolean onMenuItemClick(MenuItem item) {
1354 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001355 final Tab newTab = openTab(parent,
1356 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001357 if (newTab != parent) {
1358 parent.addChildTab(newTab);
1359 }
1360 return true;
1361 }
1362 });
1363 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001364 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001365 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1366 break;
1367 }
1368 // otherwise fall through to handle image part
1369 case WebView.HitTestResult.IMAGE_TYPE:
1370 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1371 menu.setHeaderTitle(extra);
1372 }
1373 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1374 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1375 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001376 setOnMenuItemClickListener(
1377 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001378 menu.findItem(R.id.set_wallpaper_context_menu_id).
1379 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1380 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001381 break;
1382
1383 default:
1384 Log.w(LOGTAG, "We should not get here.");
1385 break;
1386 }
1387 //update the ui
1388 mUi.onContextMenuCreated(menu);
1389 }
1390
1391 /**
1392 * As the menu can be open when loading state changes
1393 * we must manually update the state of the stop/reload menu
1394 * item
1395 */
1396 private void updateInLoadMenuItems(Menu menu) {
1397 if (menu == null) {
1398 return;
1399 }
1400 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1401 MenuItem src = mInLoad ?
1402 menu.findItem(R.id.stop_menu_id):
1403 menu.findItem(R.id.reload_menu_id);
1404 if (src != null) {
1405 dest.setIcon(src.getIcon());
1406 dest.setTitle(src.getTitle());
1407 }
1408 }
1409
John Reckb3417f02011-01-14 11:01:05 -08001410 boolean onPrepareOptionsMenu(Menu menu) {
1411 if (mOptionsMenuHandler != null) {
1412 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1413 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001414 // This happens when the user begins to hold down the menu key, so
1415 // allow them to chord to get a shortcut.
1416 mCanChord = true;
1417 // Note: setVisible will decide whether an item is visible; while
1418 // setEnabled() will decide whether an item is enabled, which also means
1419 // whether the matching shortcut key will function.
1420 switch (mMenuState) {
1421 case EMPTY_MENU:
1422 if (mCurrentMenuState != mMenuState) {
1423 menu.setGroupVisible(R.id.MAIN_MENU, false);
1424 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1425 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1426 }
1427 break;
1428 default:
1429 if (mCurrentMenuState != mMenuState) {
1430 menu.setGroupVisible(R.id.MAIN_MENU, true);
1431 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1432 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1433 }
1434 final WebView w = getCurrentTopWebView();
1435 boolean canGoBack = false;
1436 boolean canGoForward = false;
1437 boolean isHome = false;
1438 if (w != null) {
1439 canGoBack = w.canGoBack();
1440 canGoForward = w.canGoForward();
1441 isHome = mSettings.getHomePage().equals(w.getUrl());
1442 }
1443 final MenuItem back = menu.findItem(R.id.back_menu_id);
1444 back.setEnabled(canGoBack);
1445
1446 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1447 home.setEnabled(!isHome);
1448
1449 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1450 forward.setEnabled(canGoForward);
1451
1452 // decide whether to show the share link option
1453 PackageManager pm = mActivity.getPackageManager();
1454 Intent send = new Intent(Intent.ACTION_SEND);
1455 send.setType("text/plain");
1456 ResolveInfo ri = pm.resolveActivity(send,
1457 PackageManager.MATCH_DEFAULT_ONLY);
1458 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1459
1460 boolean isNavDump = mSettings.isNavDump();
1461 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1462 nav.setVisible(isNavDump);
1463 nav.setEnabled(isNavDump);
1464
1465 boolean showDebugSettings = mSettings.showDebugSettings();
1466 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1467 counter.setVisible(showDebugSettings);
1468 counter.setEnabled(showDebugSettings);
1469
John Reckb3417f02011-01-14 11:01:05 -08001470 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1471 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001472
Leon Scroggins81983762011-02-11 15:17:36 -05001473 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001474 Tab tab = getTabControl().getCurrentTab();
1475 String url = tab != null ? tab.getUrl() : null;
1476 archive.setVisible(!TextUtils.isEmpty(url)
1477 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001478 break;
1479 }
1480 mCurrentMenuState = mMenuState;
1481 return true;
1482 }
1483
1484 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001485 if (mOptionsMenuHandler != null &&
1486 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1487 return true;
1488 }
1489
Michael Kolb8233fac2010-10-26 16:08:53 -07001490 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1491 // menu remains active, so ensure comboview is dismissed
1492 // if main menu option is selected
1493 removeComboView();
1494 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001495 if (!mCanChord) {
1496 // The user has already fired a shortcut with this hold down of the
1497 // menu key.
1498 return false;
1499 }
1500 if (null == getCurrentTopWebView()) {
1501 return false;
1502 }
1503 if (mMenuIsDown) {
1504 // The shortcut action consumes the MENU. Even if it is still down,
1505 // it won't trigger the next shortcut action. In the case of the
1506 // shortcut action triggering a new activity, like Bookmarks, we
1507 // won't get onKeyUp for MENU. So it is important to reset it here.
1508 mMenuIsDown = false;
1509 }
1510 switch (item.getItemId()) {
1511 // -- Main menu
1512 case R.id.new_tab_menu_id:
1513 openTabToHomePage();
1514 break;
1515
1516 case R.id.incognito_menu_id:
1517 openIncognitoTab();
1518 break;
1519
1520 case R.id.goto_menu_id:
1521 editUrl();
1522 break;
1523
1524 case R.id.bookmarks_menu_id:
1525 bookmarksOrHistoryPicker(false);
1526 break;
1527
1528 case R.id.active_tabs_menu_id:
1529 showActiveTabsPage();
1530 break;
1531
1532 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001533 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001534 break;
1535
1536 case R.id.stop_reload_menu_id:
1537 if (mInLoad) {
1538 stopLoading();
1539 } else {
1540 getCurrentTopWebView().reload();
1541 }
1542 break;
1543
1544 case R.id.back_menu_id:
1545 getCurrentTopWebView().goBack();
1546 break;
1547
1548 case R.id.forward_menu_id:
1549 getCurrentTopWebView().goForward();
1550 break;
1551
1552 case R.id.close_menu_id:
1553 // Close the subwindow if it exists.
1554 if (mTabControl.getCurrentSubWindow() != null) {
1555 dismissSubWindow(mTabControl.getCurrentTab());
1556 break;
1557 }
1558 closeCurrentTab();
1559 break;
1560
1561 case R.id.homepage_menu_id:
1562 Tab current = mTabControl.getCurrentTab();
1563 if (current != null) {
1564 dismissSubWindow(current);
1565 loadUrl(current.getWebView(), mSettings.getHomePage());
1566 }
1567 break;
1568
1569 case R.id.preferences_menu_id:
1570 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1571 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1572 getCurrentTopWebView().getUrl());
1573 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1574 break;
1575
1576 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001577 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001578 break;
1579
Leon Scrogginsac993842011-02-02 12:54:07 -05001580 case R.id.save_webarchive_menu_id:
1581 String state = Environment.getExternalStorageState();
1582 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1583 Log.e(LOGTAG, "External storage not mounted");
1584 Toast.makeText(mActivity, R.string.webarchive_failed,
1585 Toast.LENGTH_SHORT).show();
1586 break;
1587 }
1588 final String directory = Environment.getExternalStoragePublicDirectory(
1589 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1590 File dir = new File(directory);
1591 if (!dir.exists() && !dir.mkdirs()) {
1592 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1593 Toast.makeText(mActivity, R.string.webarchive_failed,
1594 Toast.LENGTH_SHORT).show();
1595 break;
1596 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001597 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001598 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001599 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001600 topWebView.saveWebArchive(directory, true,
1601 new ValueCallback<String>() {
1602 @Override
1603 public void onReceiveValue(final String value) {
1604 if (value != null) {
1605 File file = new File(value);
1606 final long length = file.length();
1607 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001608 Toast.makeText(mActivity, R.string.webarchive_saved,
1609 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001610 final DownloadManager manager = (DownloadManager) mActivity
1611 .getSystemService(Context.DOWNLOAD_SERVICE);
1612 new Thread("Add WebArchive to download manager") {
1613 @Override
1614 public void run() {
1615 manager.completedDownload(null == title ? value : title,
1616 value, true, "application/x-webarchive-xml",
1617 value, length, true);
1618 }
1619 }.start();
1620 return;
1621 }
1622 }
John Reck51d8bad2011-02-28 15:47:47 -08001623 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001624 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001625 }
1626 });
1627 break;
1628
Michael Kolb8233fac2010-10-26 16:08:53 -07001629 case R.id.page_info_menu_id:
1630 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1631 false);
1632 break;
1633
1634 case R.id.classic_history_menu_id:
1635 bookmarksOrHistoryPicker(true);
1636 break;
1637
1638 case R.id.title_bar_share_page_url:
1639 case R.id.share_page_menu_id:
1640 Tab currentTab = mTabControl.getCurrentTab();
1641 if (null == currentTab) {
1642 mCanChord = false;
1643 return false;
1644 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001645 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001646 break;
1647
1648 case R.id.dump_nav_menu_id:
1649 getCurrentTopWebView().debugDump();
1650 break;
1651
1652 case R.id.dump_counters_menu_id:
1653 getCurrentTopWebView().dumpV8Counters();
1654 break;
1655
1656 case R.id.zoom_in_menu_id:
1657 getCurrentTopWebView().zoomIn();
1658 break;
1659
1660 case R.id.zoom_out_menu_id:
1661 getCurrentTopWebView().zoomOut();
1662 break;
1663
1664 case R.id.view_downloads_menu_id:
1665 viewDownloads();
1666 break;
1667
1668 case R.id.window_one_menu_id:
1669 case R.id.window_two_menu_id:
1670 case R.id.window_three_menu_id:
1671 case R.id.window_four_menu_id:
1672 case R.id.window_five_menu_id:
1673 case R.id.window_six_menu_id:
1674 case R.id.window_seven_menu_id:
1675 case R.id.window_eight_menu_id:
1676 {
1677 int menuid = item.getItemId();
1678 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1679 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1680 Tab desiredTab = mTabControl.getTab(id);
1681 if (desiredTab != null &&
1682 desiredTab != mTabControl.getCurrentTab()) {
1683 switchToTab(id);
1684 }
1685 break;
1686 }
1687 }
1688 }
1689 break;
1690
1691 default:
1692 return false;
1693 }
1694 mCanChord = false;
1695 return true;
1696 }
1697
1698 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001699 // Let the History and Bookmark fragments handle menus they created.
1700 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1701 return false;
1702 }
1703
Michael Kolb8233fac2010-10-26 16:08:53 -07001704 // chording is not an issue with context menus, but we use the same
1705 // options selector, so set mCanChord to true so we can access them.
1706 mCanChord = true;
1707 int id = item.getItemId();
1708 boolean result = true;
1709 switch (id) {
1710 // For the context menu from the title bar
1711 case R.id.title_bar_copy_page_url:
1712 Tab currentTab = mTabControl.getCurrentTab();
1713 if (null == currentTab) {
1714 result = false;
1715 break;
1716 }
1717 WebView mainView = currentTab.getWebView();
1718 if (null == mainView) {
1719 result = false;
1720 break;
1721 }
1722 copy(mainView.getUrl());
1723 break;
1724 // -- Browser context menu
1725 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001726 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001727 case R.id.copy_link_context_menu_id:
1728 final WebView webView = getCurrentTopWebView();
1729 if (null == webView) {
1730 result = false;
1731 break;
1732 }
1733 final HashMap<String, WebView> hrefMap =
1734 new HashMap<String, WebView>();
1735 hrefMap.put("webview", webView);
1736 final Message msg = mHandler.obtainMessage(
1737 FOCUS_NODE_HREF, id, 0, hrefMap);
1738 webView.requestFocusNodeHref(msg);
1739 break;
1740
1741 default:
1742 // For other context menus
1743 result = onOptionsItemSelected(item);
1744 }
1745 mCanChord = false;
1746 return result;
1747 }
1748
1749 /**
1750 * support programmatically opening the context menu
1751 */
1752 public void openContextMenu(View view) {
1753 mActivity.openContextMenu(view);
1754 }
1755
1756 /**
1757 * programmatically open the options menu
1758 */
1759 public void openOptionsMenu() {
1760 mActivity.openOptionsMenu();
1761 }
1762
1763 public boolean onMenuOpened(int featureId, Menu menu) {
1764 if (mOptionsMenuOpen) {
1765 if (mConfigChanged) {
1766 // We do not need to make any changes to the state of the
1767 // title bar, since the only thing that happened was a
1768 // change in orientation
1769 mConfigChanged = false;
1770 } else {
1771 if (!mExtendedMenuOpen) {
1772 mExtendedMenuOpen = true;
1773 mUi.onExtendedMenuOpened();
1774 } else {
1775 // Switching the menu back to icon view, so show the
1776 // title bar once again.
1777 mExtendedMenuOpen = false;
1778 mUi.onExtendedMenuClosed(mInLoad);
1779 mUi.onOptionsMenuOpened();
1780 }
1781 }
1782 } else {
1783 // The options menu is closed, so open it, and show the title
1784 mOptionsMenuOpen = true;
1785 mConfigChanged = false;
1786 mExtendedMenuOpen = false;
1787 mUi.onOptionsMenuOpened();
1788 }
1789 return true;
1790 }
1791
1792 public void onOptionsMenuClosed(Menu menu) {
1793 mOptionsMenuOpen = false;
1794 mUi.onOptionsMenuClosed(mInLoad);
1795 }
1796
1797 public void onContextMenuClosed(Menu menu) {
1798 mUi.onContextMenuClosed(menu, mInLoad);
1799 }
1800
1801 // Helper method for getting the top window.
1802 @Override
1803 public WebView getCurrentTopWebView() {
1804 return mTabControl.getCurrentTopWebView();
1805 }
1806
1807 @Override
1808 public WebView getCurrentWebView() {
1809 return mTabControl.getCurrentWebView();
1810 }
1811
1812 /*
1813 * This method is called as a result of the user selecting the options
1814 * menu to see the download window. It shows the download window on top of
1815 * the current window.
1816 */
1817 void viewDownloads() {
1818 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1819 mActivity.startActivity(intent);
1820 }
1821
1822 // action mode
1823
1824 void onActionModeStarted(ActionMode mode) {
1825 mUi.onActionModeStarted(mode);
1826 mActionMode = mode;
1827 }
1828
1829 /*
1830 * True if a custom ActionMode (i.e. find or select) is in use.
1831 */
1832 @Override
1833 public boolean isInCustomActionMode() {
1834 return mActionMode != null;
1835 }
1836
1837 /*
1838 * End the current ActionMode.
1839 */
1840 @Override
1841 public void endActionMode() {
1842 if (mActionMode != null) {
1843 mActionMode.finish();
1844 }
1845 }
1846
1847 /*
1848 * Called by find and select when they are finished. Replace title bars
1849 * as necessary.
1850 */
1851 public void onActionModeFinished(ActionMode mode) {
1852 if (!isInCustomActionMode()) return;
1853 mUi.onActionModeFinished(mInLoad);
1854 mActionMode = null;
1855 }
1856
1857 boolean isInLoad() {
1858 return mInLoad;
1859 }
1860
1861 // bookmark handling
1862
1863 /**
1864 * add the current page as a bookmark to the given folder id
1865 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001866 * @param canBeAnEdit If true, check to see whether the site is already
1867 * bookmarked, and if it is, edit that bookmark. If false, and
1868 * the site is already bookmarked, do not attempt to edit the
1869 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001870 */
1871 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001872 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001873 Intent i = new Intent(mActivity,
1874 AddBookmarkPage.class);
1875 WebView w = getCurrentTopWebView();
1876 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1877 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1878 String touchIconUrl = w.getTouchIconUrl();
1879 if (touchIconUrl != null) {
1880 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1881 WebSettings settings = w.getSettings();
1882 if (settings != null) {
1883 i.putExtra(AddBookmarkPage.USER_AGENT,
1884 settings.getUserAgentString());
1885 }
1886 }
1887 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1888 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1889 getDesiredThumbnailHeight(mActivity)));
1890 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1891 i.putExtra(BrowserContract.Bookmarks.PARENT,
1892 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001893 if (canBeAnEdit) {
1894 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1895 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001896 // Put the dialog at the upper right of the screen, covering the
1897 // star on the title bar.
1898 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1899 mActivity.startActivity(i);
1900 }
1901
1902 // file chooser
1903 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1904 mUploadHandler = new UploadHandler(this);
1905 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1906 }
1907
1908 // thumbnails
1909
1910 /**
1911 * Return the desired width for thumbnail screenshots, which are stored in
1912 * the database, and used on the bookmarks screen.
1913 * @param context Context for finding out the density of the screen.
1914 * @return desired width for thumbnail screenshot.
1915 */
1916 static int getDesiredThumbnailWidth(Context context) {
1917 return context.getResources().getDimensionPixelOffset(
1918 R.dimen.bookmarkThumbnailWidth);
1919 }
1920
1921 /**
1922 * Return the desired height for thumbnail screenshots, which are stored in
1923 * the database, and used on the bookmarks screen.
1924 * @param context Context for finding out the density of the screen.
1925 * @return desired height for thumbnail screenshot.
1926 */
1927 static int getDesiredThumbnailHeight(Context context) {
1928 return context.getResources().getDimensionPixelOffset(
1929 R.dimen.bookmarkThumbnailHeight);
1930 }
1931
1932 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001933 // We render to a bitmap 2x the desired size so that we can then
1934 // re-scale it with filtering since canvas.scale doesn't filter
1935 // This helps reduce aliasing at the cost of being slightly blurry
1936 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001937 Picture thumbnail = view.capturePicture();
1938 if (thumbnail == null) {
1939 return null;
1940 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001941 width *= filter_scale;
1942 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001943 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1944 Canvas canvas = new Canvas(bm);
1945 // May need to tweak these values to determine what is the
1946 // best scale factor
1947 int thumbnailWidth = thumbnail.getWidth();
1948 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001949 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001950 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001951 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001952 } else {
1953 return null;
1954 }
John Reckfe49ab42010-11-16 17:09:37 -08001955
Michael Kolb8233fac2010-10-26 16:08:53 -07001956 if (view.getWidth() > view.getHeight() &&
1957 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1958 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001959 // than the height of the view, center the thumnail and crop the sides
1960 scaleFactor = (float) height / (float)thumbnailHeight;
1961 float wx = (thumbnailWidth * scaleFactor) - width;
1962 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 }
1964
John Reckfe49ab42010-11-16 17:09:37 -08001965 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001966
1967 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001968 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1969 height / filter_scale, true);
1970 bm.recycle();
1971 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001972 }
1973
John Reck34ef2672011-02-10 11:30:55 -08001974 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001975 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001976 // FIXME: Would like to make sure there is actually something to
1977 // draw, but the API for that (WebViewCore.pictureReady()) is not
1978 // currently accessible here.
1979
John Reck34ef2672011-02-10 11:30:55 -08001980 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001981 if (view == null) {
1982 // Tab was destroyed
1983 return;
1984 }
John Reck34ef2672011-02-10 11:30:55 -08001985 final String url = tab.getUrl();
1986 final String originalUrl = view.getOriginalUrl();
1987
1988 if (TextUtils.isEmpty(url)) {
1989 return;
1990 }
1991
1992 // Only update thumbnails for web urls (http(s)://), not for
1993 // about:, javascript:, data:, etc...
1994 // Unless it is a bookmarked site, then always update
1995 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1996 return;
1997 }
1998
Michael Kolb8233fac2010-10-26 16:08:53 -07001999 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2000 getDesiredThumbnailHeight(mActivity));
2001 if (bm == null) {
2002 return;
2003 }
2004
2005 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002006 new AsyncTask<Void, Void, Void>() {
2007 @Override
2008 protected Void doInBackground(Void... unused) {
2009 Cursor cursor = null;
2010 try {
2011 // TODO: Clean this up
2012 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2013 if (cursor != null && cursor.moveToFirst()) {
2014 final ByteArrayOutputStream os =
2015 new ByteArrayOutputStream();
2016 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002017
John Reck34ef2672011-02-10 11:30:55 -08002018 ContentValues values = new ContentValues();
2019 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002020
John Reck34ef2672011-02-10 11:30:55 -08002021 do {
John Reck617fd832011-02-16 14:35:59 -08002022 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002023 cr.update(Images.CONTENT_URI, values, null, null);
2024 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002025 }
John Reck34ef2672011-02-10 11:30:55 -08002026 } catch (IllegalStateException e) {
2027 // Ignore
2028 } finally {
2029 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002030 }
John Reck34ef2672011-02-10 11:30:55 -08002031 return null;
2032 }
2033 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002034 }
2035
2036 private class Copy implements OnMenuItemClickListener {
2037 private CharSequence mText;
2038
2039 public boolean onMenuItemClick(MenuItem item) {
2040 copy(mText);
2041 return true;
2042 }
2043
2044 public Copy(CharSequence toCopy) {
2045 mText = toCopy;
2046 }
2047 }
2048
Leon Scroggins63c02662010-11-18 15:16:27 -05002049 private static class Download implements OnMenuItemClickListener {
2050 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002051 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002052 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002053
2054 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002055 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002056 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002057 return true;
2058 }
2059
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002060 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002061 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002062 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002063 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002064 }
2065 }
2066
Cary Clark8974d282010-11-22 10:46:05 -05002067 private static class SelectText implements OnMenuItemClickListener {
2068 private WebView mWebView;
2069
2070 public boolean onMenuItemClick(MenuItem item) {
2071 if (mWebView != null) {
2072 return mWebView.selectText();
2073 }
2074 return false;
2075 }
2076
2077 public SelectText(WebView webView) {
2078 mWebView = webView;
2079 }
2080
2081 }
2082
Michael Kolb8233fac2010-10-26 16:08:53 -07002083 /********************** TODO: UI stuff *****************************/
2084
2085 // these methods have been copied, they still need to be cleaned up
2086
2087 /****************** tabs ***************************************************/
2088
2089 // basic tab interactions:
2090
2091 // it is assumed that tabcontrol already knows about the tab
2092 protected void addTab(Tab tab) {
2093 mUi.addTab(tab);
2094 }
2095
2096 protected void removeTab(Tab tab) {
2097 mUi.removeTab(tab);
2098 mTabControl.removeTab(tab);
2099 }
2100
2101 protected void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002102 // monkey protection against delayed start
2103 if (tab != null) {
2104 mTabControl.setCurrentTab(tab);
2105 // the tab is guaranteed to have a webview after setCurrentTab
2106 mUi.setActiveTab(tab);
2107 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002108 }
2109
2110 protected void closeEmptyChildTab() {
2111 Tab current = mTabControl.getCurrentTab();
2112 if (current != null
2113 && current.getWebView().copyBackForwardList().getSize() == 0) {
2114 Tab parent = current.getParentTab();
2115 if (parent != null) {
2116 switchToTab(mTabControl.getTabIndex(parent));
2117 closeTab(current);
2118 }
2119 }
2120 }
2121
2122 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002123 // Dismiss the subwindow if applicable.
2124 dismissSubWindow(appTab);
2125 // Since we might kill the WebView, remove it from the
2126 // content view first.
2127 mUi.detachTab(appTab);
2128 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002129 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002130 // TODO: analyze why the remove and add are necessary
2131 mUi.attachTab(appTab);
2132 if (mTabControl.getCurrentTab() != appTab) {
2133 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002134 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002135 } else {
2136 // If the tab was the current tab, we have to attach
2137 // it to the view system again.
2138 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002139 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002140 }
2141 }
2142
2143 // Remove the sub window if it exists. Also called by TabControl when the
2144 // user clicks the 'X' to dismiss a sub window.
2145 public void dismissSubWindow(Tab tab) {
2146 removeSubWindow(tab);
2147 // dismiss the subwindow. This will destroy the WebView.
2148 tab.dismissSubWindow();
2149 getCurrentTopWebView().requestFocus();
2150 }
2151
2152 @Override
2153 public void removeSubWindow(Tab t) {
2154 if (t.getSubWebView() != null) {
2155 mUi.removeSubWindow(t.getSubViewContainer());
2156 }
2157 }
2158
2159 @Override
2160 public void attachSubWindow(Tab tab) {
2161 if (tab.getSubWebView() != null) {
2162 mUi.attachSubWindow(tab.getSubViewContainer());
2163 getCurrentTopWebView().requestFocus();
2164 }
2165 }
2166
Michael Kolb843510f2010-12-09 10:51:49 -08002167 @Override
2168 public Tab openTabToHomePage() {
2169 // check for max tabs
2170 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002171 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2172 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002173 } else {
2174 mUi.showMaxTabsWarning();
2175 return null;
2176 }
2177 }
2178
Michael Kolb18eb3772010-12-10 14:29:51 -08002179 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2180 if (mSettings.openInBackground() && !forceForeground) {
2181 Tab tab = mTabControl.createNewTab(false, null, null,
2182 (parent != null) && parent.isPrivateBrowsingEnabled());
2183 if (tab != null) {
2184 addTab(tab);
2185 WebView view = tab.getWebView();
2186 loadUrl(view, url);
2187 }
2188 return tab;
2189 } else {
2190 return openTabAndShow(parent, new UrlData(url), false, null);
2191 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002192 }
2193
Michael Kolb18eb3772010-12-10 14:29:51 -08002194
Michael Kolb8233fac2010-10-26 16:08:53 -07002195 // This method does a ton of stuff. It will attempt to create a new tab
2196 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2197 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002198 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2199 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002200 final Tab currentTab = mTabControl.getCurrentTab();
2201 if (mTabControl.canCreateNewTab()) {
2202 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002203 urlData.mUrl,
2204 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002205 WebView webview = tab.getWebView();
2206 // We must set the new tab as the current tab to reflect the old
2207 // animation behavior.
2208 addTab(tab);
2209 setActiveTab(tab);
Patrick Scottcd135082011-01-31 18:21:58 -05002210
2211 // Callback to load the url data.
2212 final Runnable load = new Runnable() {
2213 @Override public void run() {
2214 if (!urlData.isEmpty()) {
2215 loadUrlDataIn(tab, urlData);
2216 }
2217 }
2218 };
2219
2220 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings, load);
Michael Kolb8233fac2010-10-26 16:08:53 -07002221 return tab;
2222 } else {
2223 // Get rid of the subwindow if it exists
2224 dismissSubWindow(currentTab);
2225 if (!urlData.isEmpty()) {
2226 // Load the given url.
2227 loadUrlDataIn(currentTab, urlData);
2228 }
2229 return currentTab;
2230 }
2231 }
2232
Michael Kolb8233fac2010-10-26 16:08:53 -07002233 @Override
2234 public Tab openIncognitoTab() {
2235 if (mTabControl.canCreateNewTab()) {
2236 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002237 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002238 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002239 addTab(tab);
2240 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002241 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002242 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002243 } else {
2244 mUi.showMaxTabsWarning();
2245 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002246 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002247 }
2248
2249 /**
2250 * @param index Index of the tab to change to, as defined by
2251 * mTabControl.getTabIndex(Tab t).
2252 * @return boolean True if we successfully switched to a different tab. If
2253 * the indexth tab is null, or if that tab is the same as
2254 * the current one, return false.
2255 */
2256 @Override
2257 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002258 // hide combo view if open
2259 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002260 Tab tab = mTabControl.getTab(index);
2261 Tab currentTab = mTabControl.getCurrentTab();
2262 if (tab == null || tab == currentTab) {
2263 return false;
2264 }
2265 setActiveTab(tab);
2266 return true;
2267 }
2268
2269 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002270 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002271 // hide combo view if open
2272 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002273 final Tab current = mTabControl.getCurrentTab();
2274 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002275 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002276 return;
2277 }
2278 final Tab parent = current.getParentTab();
2279 int indexToShow = -1;
2280 if (parent != null) {
2281 indexToShow = mTabControl.getTabIndex(parent);
2282 } else {
2283 final int currentIndex = mTabControl.getCurrentIndex();
2284 // Try to move to the tab to the right
2285 indexToShow = currentIndex + 1;
2286 if (indexToShow > mTabControl.getTabCount() - 1) {
2287 // Try to move to the tab to the left
2288 indexToShow = currentIndex - 1;
2289 }
2290 }
2291 if (switchToTab(indexToShow)) {
2292 // Close window
2293 closeTab(current);
2294 }
2295 }
2296
2297 /**
2298 * Close the tab, remove its associated title bar, and adjust mTabControl's
2299 * current tab to a valid value.
2300 */
2301 @Override
2302 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002303 // hide combo view if open
2304 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002305 int currentIndex = mTabControl.getCurrentIndex();
2306 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002307 Tab newtab = mTabControl.getTab(currentIndex);
2308 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002309 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002310 }
2311
2312 /**************** TODO: Url loading clean up *******************************/
2313
2314 // Called when loading from context menu or LOAD_URL message
2315 protected void loadUrlFromContext(WebView view, String url) {
2316 // In case the user enters nothing.
2317 if (url != null && url.length() != 0 && view != null) {
2318 url = UrlUtils.smartUrlFilter(url);
2319 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2320 loadUrl(view, url);
2321 }
2322 }
2323 }
2324
2325 /**
2326 * Load the URL into the given WebView and update the title bar
2327 * to reflect the new load. Call this instead of WebView.loadUrl
2328 * directly.
2329 * @param view The WebView used to load url.
2330 * @param url The URL to load.
2331 */
2332 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002333 view.loadUrl(url);
2334 }
2335
2336 /**
2337 * Load UrlData into a Tab and update the title bar to reflect the new
2338 * load. Call this instead of UrlData.loadIn directly.
2339 * @param t The Tab used to load.
2340 * @param data The UrlData being loaded.
2341 */
2342 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002343 data.loadIn(t);
2344 }
2345
John Reck30c714c2010-12-16 17:30:34 -08002346 @Override
2347 public void onUserCanceledSsl(Tab tab) {
2348 WebView web = tab.getWebView();
2349 // TODO: Figure out the "right" behavior
2350 if (web.canGoBack()) {
2351 web.goBack();
2352 } else {
2353 web.loadUrl(mSettings.getHomePage());
2354 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002355 }
2356
2357 void goBackOnePageOrQuit() {
2358 Tab current = mTabControl.getCurrentTab();
2359 if (current == null) {
2360 /*
2361 * Instead of finishing the activity, simply push this to the back
2362 * of the stack and let ActivityManager to choose the foreground
2363 * activity. As BrowserActivity is singleTask, it will be always the
2364 * root of the task. So we can use either true or false for
2365 * moveTaskToBack().
2366 */
2367 mActivity.moveTaskToBack(true);
2368 return;
2369 }
2370 WebView w = current.getWebView();
2371 if (w.canGoBack()) {
2372 w.goBack();
2373 } else {
2374 // Check to see if we are closing a window that was created by
2375 // another window. If so, we switch back to that window.
2376 Tab parent = current.getParentTab();
2377 if (parent != null) {
2378 switchToTab(mTabControl.getTabIndex(parent));
2379 // Now we close the other tab
2380 closeTab(current);
2381 } else {
2382 if (current.closeOnExit()) {
Patrick Scottfc1518a2011-02-28 13:57:03 -05002383 // This will finish the activity if there is only one tab
2384 // open or it will switch to the next available tab if
2385 // available.
Michael Kolb96683f72011-02-15 14:24:35 -08002386 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002387 }
2388 /*
2389 * Instead of finishing the activity, simply push this to the back
2390 * of the stack and let ActivityManager to choose the foreground
2391 * activity. As BrowserActivity is singleTask, it will be always the
2392 * root of the task. So we can use either true or false for
2393 * moveTaskToBack().
2394 */
2395 mActivity.moveTaskToBack(true);
2396 }
2397 }
2398 }
2399
2400 /**
2401 * Feed the previously stored results strings to the BrowserProvider so that
2402 * the SearchDialog will show them instead of the standard searches.
2403 * @param result String to show on the editable line of the SearchDialog.
2404 */
2405 @Override
2406 public void showVoiceSearchResults(String result) {
2407 ContentProviderClient client = mActivity.getContentResolver()
2408 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2409 ContentProvider prov = client.getLocalContentProvider();
2410 BrowserProvider bp = (BrowserProvider) prov;
2411 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2412 client.release();
2413
2414 Bundle bundle = createGoogleSearchSourceBundle(
2415 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2416 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2417 startSearch(result, false, bundle, false);
2418 }
2419
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002420 @Override
2421 public void startSearch(String url) {
2422 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
2423 null, false);
2424 }
2425
Michael Kolb8233fac2010-10-26 16:08:53 -07002426 private void startSearch(String initialQuery, boolean selectInitialQuery,
2427 Bundle appSearchData, boolean globalSearch) {
2428 if (appSearchData == null) {
2429 appSearchData = createGoogleSearchSourceBundle(
2430 GOOGLE_SEARCH_SOURCE_TYPE);
2431 }
2432
2433 SearchEngine searchEngine = mSettings.getSearchEngine();
2434 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2435 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2436 }
2437 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2438 globalSearch);
2439 }
2440
2441 private Bundle createGoogleSearchSourceBundle(String source) {
2442 Bundle bundle = new Bundle();
2443 bundle.putString(Search.SOURCE, source);
2444 return bundle;
2445 }
2446
2447 /**
2448 * handle key events in browser
2449 *
2450 * @param keyCode
2451 * @param event
2452 * @return true if handled, false to pass to super
2453 */
2454 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002455 boolean noModifiers = event.hasNoModifiers();
2456
Michael Kolb8233fac2010-10-26 16:08:53 -07002457 // Even if MENU is already held down, we need to call to super to open
2458 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002459 if (!noModifiers
2460 && ((KeyEvent.KEYCODE_MENU == keyCode)
2461 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2462 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002463 mMenuIsDown = true;
2464 return false;
2465 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002466
Cary Clark8ff8c662010-12-29 15:03:05 -05002467 WebView webView = getCurrentTopWebView();
2468 if (webView == null) return false;
2469
Cary Clark160bbb92011-01-10 11:17:07 -05002470 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2471 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002472
Michael Kolb8233fac2010-10-26 16:08:53 -07002473 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002474 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002475 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002476 stopLoading();
2477 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002478 case KeyEvent.KEYCODE_SPACE:
2479 // WebView/WebTextView handle the keys in the KeyDown. As
2480 // the Activity's shortcut keys are only handled when WebView
2481 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002482 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002483 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002484 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002485 pageDown();
2486 }
2487 return true;
2488 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002489 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002490 event.startTracking();
2491 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002492 case KeyEvent.KEYCODE_DPAD_LEFT:
2493 if (ctrl) {
2494 webView.goBack();
2495 return true;
2496 }
2497 break;
2498 case KeyEvent.KEYCODE_DPAD_RIGHT:
2499 if (ctrl) {
2500 webView.goForward();
2501 return true;
2502 }
2503 break;
2504 case KeyEvent.KEYCODE_A:
2505 if (ctrl) {
2506 webView.selectAll();
2507 return true;
2508 }
2509 break;
Michael Kolba4183062011-01-16 10:43:21 -08002510// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002511 case KeyEvent.KEYCODE_C:
2512 if (ctrl) {
2513 webView.copySelection();
2514 return true;
2515 }
2516 break;
Michael Kolba4183062011-01-16 10:43:21 -08002517// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002518// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002519// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002520// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002521// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002522// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002523// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002524// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002525// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002526// case KeyEvent.KEYCODE_M: // unused
2527// case KeyEvent.KEYCODE_N: // in Chrome: new window
2528// case KeyEvent.KEYCODE_O: // in Chrome: open file
2529// case KeyEvent.KEYCODE_P: // in Chrome: print page
2530// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002531// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002532// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2533 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002534 // we can't use the ctrl/shift flags, they check for
2535 // exclusive use of a modifier
2536 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002537 if (event.isShiftPressed()) {
2538 openIncognitoTab();
2539 } else {
2540 openTabToHomePage();
2541 }
2542 return true;
2543 }
2544 break;
2545// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2546// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolba4183062011-01-16 10:43:21 -08002547// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002548// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2549// case KeyEvent.KEYCODE_Y: // unused
2550// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002551 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002552 // it is a regular key and webview is not null
2553 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002554 }
2555
John Recke6bf4ab2011-02-24 15:48:05 -08002556 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2557 switch(keyCode) {
2558 case KeyEvent.KEYCODE_BACK:
2559 if (mUi.showsWeb()) {
2560 bookmarksOrHistoryPicker(true);
2561 return true;
2562 }
2563 break;
2564 }
2565 return false;
2566 }
2567
Michael Kolb8233fac2010-10-26 16:08:53 -07002568 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002569 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002570 switch(keyCode) {
2571 case KeyEvent.KEYCODE_MENU:
2572 mMenuIsDown = false;
2573 break;
2574 case KeyEvent.KEYCODE_BACK:
2575 if (event.isTracking() && !event.isCanceled()) {
2576 onBackKey();
2577 return true;
2578 }
2579 break;
2580 }
2581 return false;
2582 }
2583
2584 public boolean isMenuDown() {
2585 return mMenuIsDown;
2586 }
2587
Ben Murdoch8029a772010-11-16 11:58:21 +00002588 public void setupAutoFill(Message message) {
2589 // Open the settings activity at the AutoFill profile fragment so that
2590 // the user can create a new profile. When they return, we will dispatch
2591 // the message so that we can autofill the form using their new profile.
2592 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2593 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2594 AutoFillSettingsFragment.class.getName());
2595 mAutoFillSetupMessage = message;
2596 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2597 }
John Reckb3417f02011-01-14 11:01:05 -08002598
2599 @Override
2600 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2601 mOptionsMenuHandler = handler;
2602 }
2603
2604 @Override
2605 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2606 if (mOptionsMenuHandler == handler) {
2607 mOptionsMenuHandler = null;
2608 }
2609 }
2610
Michael Kolb8233fac2010-10-26 16:08:53 -07002611}