blob: 74a66b16f07c81c5490ca6c55afe284f7667fac6 [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;
46import android.os.Handler;
47import android.os.Message;
48import android.os.PowerManager;
49import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000050import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070051import android.provider.Browser;
52import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070053import android.provider.BrowserContract.Images;
54import android.provider.ContactsContract;
55import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080056import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070057import android.speech.RecognizerResultsIntent;
58import android.text.TextUtils;
59import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080060import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070061import android.view.ActionMode;
62import android.view.ContextMenu;
63import android.view.ContextMenu.ContextMenuInfo;
64import android.view.Gravity;
65import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070066import android.view.Menu;
67import android.view.MenuInflater;
68import android.view.MenuItem;
69import android.view.MenuItem.OnMenuItemClickListener;
70import android.view.View;
71import android.webkit.CookieManager;
72import android.webkit.CookieSyncManager;
73import android.webkit.HttpAuthHandler;
74import android.webkit.SslErrorHandler;
75import android.webkit.ValueCallback;
76import android.webkit.WebChromeClient;
77import android.webkit.WebIconDatabase;
78import android.webkit.WebSettings;
79import android.webkit.WebView;
Michael Kolb8233fac2010-10-26 16:08:53 -070080
81import java.io.ByteArrayOutputStream;
82import java.io.File;
83import java.net.URLEncoder;
84import java.util.Calendar;
85import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080086import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070087
88/**
89 * Controller for browser
90 */
91public class Controller
92 implements WebViewController, UiController {
93
94 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -080095 private static final String SEND_APP_ID_EXTRA =
96 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
97
Michael Kolb8233fac2010-10-26 16:08:53 -070098
99 // public message ids
100 public final static int LOAD_URL = 1001;
101 public final static int STOP_LOAD = 1002;
102
103 // Message Ids
104 private static final int FOCUS_NODE_HREF = 102;
105 private static final int RELEASE_WAKELOCK = 107;
106
107 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
108
109 private static final int OPEN_BOOKMARKS = 201;
110
111 private static final int EMPTY_MENU = -1;
112
Michael Kolb8233fac2010-10-26 16:08:53 -0700113 // activity requestCode
114 final static int PREFERENCES_PAGE = 3;
115 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000116 final static int AUTOFILL_SETUP = 5;
117
Michael Kolb8233fac2010-10-26 16:08:53 -0700118 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
119
120 // As the ids are dynamically created, we can't guarantee that they will
121 // be in sequence, so this static array maps ids to a window number.
122 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
123 { R.id.window_one_menu_id, R.id.window_two_menu_id,
124 R.id.window_three_menu_id, R.id.window_four_menu_id,
125 R.id.window_five_menu_id, R.id.window_six_menu_id,
126 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
127
128 // "source" parameter for Google search through search key
129 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
130 // "source" parameter for Google search through simplily type
131 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
132
133 private Activity mActivity;
134 private UI mUi;
135 private TabControl mTabControl;
136 private BrowserSettings mSettings;
137 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800138 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700139
140 private WakeLock mWakeLock;
141
142 private UrlHandler mUrlHandler;
143 private UploadHandler mUploadHandler;
144 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700145 private PageDialogsHandler mPageDialogsHandler;
146 private NetworkStateHandler mNetworkHandler;
147
Ben Murdoch8029a772010-11-16 11:58:21 +0000148 private Message mAutoFillSetupMessage;
149
Michael Kolb8233fac2010-10-26 16:08:53 -0700150 private boolean mShouldShowErrorConsole;
151
152 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
153
154 // FIXME, temp address onPrepareMenu performance problem.
155 // When we move everything out of view, we should rewrite this.
156 private int mCurrentMenuState = 0;
157 private int mMenuState = R.id.MAIN_MENU;
158 private int mOldMenuState = EMPTY_MENU;
159 private Menu mCachedMenu;
160
161 // Used to prevent chording to result in firing two shortcuts immediately
162 // one after another. Fixes bug 1211714.
163 boolean mCanChord;
164 private boolean mMenuIsDown;
165
166 // For select and find, we keep track of the ActionMode so that
167 // finish() can be called as desired.
168 private ActionMode mActionMode;
169
170 /**
171 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
172 * of whether the configuration has changed. The first onMenuOpened call
173 * after a configuration change is simply a reopening of the same menu
174 * (i.e. mIconView did not change).
175 */
176 private boolean mConfigChanged;
177
178 /**
179 * Keeps track of whether the options menu is open. This is important in
180 * determining whether to show or hide the title bar overlay
181 */
182 private boolean mOptionsMenuOpen;
183
184 /**
185 * Whether or not the options menu is in its bigger, popup menu form. When
186 * true, we want the title bar overlay to be gone. When false, we do not.
187 * Only meaningful if mOptionsMenuOpen is true.
188 */
189 private boolean mExtendedMenuOpen;
190
191 private boolean mInLoad;
192
193 private boolean mActivityPaused = true;
194 private boolean mLoadStopped;
195
196 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500197 // Checks to see when the bookmarks database has changed, and updates the
198 // Tabs' notion of whether they represent bookmarked sites.
199 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800200 private DataController mDataController;
Michael Kolb8233fac2010-10-26 16:08:53 -0700201
202 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
203 @Override
204 public Void doInBackground(File... files) {
205 if (files != null) {
206 for (File f : files) {
207 if (!f.delete()) {
208 Log.e(LOGTAG, f.getPath() + " was not deleted");
209 }
210 }
211 }
212 return null;
213 }
214 }
215
216 public Controller(Activity browser) {
217 mActivity = browser;
218 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800219 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700220 mTabControl = new TabControl(this);
221 mSettings.setController(this);
222
223 mUrlHandler = new UrlHandler(this);
224 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700225 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
226
227 PowerManager pm = (PowerManager) mActivity
228 .getSystemService(Context.POWER_SERVICE);
229 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
230
231 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500232 mBookmarksObserver = new ContentObserver(mHandler) {
233 @Override
234 public void onChange(boolean selfChange) {
235 int size = mTabControl.getTabCount();
236 for (int i = 0; i < size; i++) {
237 mTabControl.getTab(i).updateBookmarkedStatus();
238 }
239 }
240
241 };
242 browser.getContentResolver().registerContentObserver(
243 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700244
245 mNetworkHandler = new NetworkStateHandler(mActivity, this);
246 // Start watching the default geolocation permissions
247 mSystemAllowGeolocationOrigins =
248 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
249 mSystemAllowGeolocationOrigins.start();
250
251 retainIconsOnStartup();
252 }
253
Patrick Scott7d50a932011-02-04 09:27:26 -0500254 void start(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700255 // Unless the last browser usage was within 24 hours, destroy any
256 // remaining incognito tabs.
257
258 Calendar lastActiveDate = icicle != null ?
259 (Calendar) icicle.getSerializable("lastActiveDate") : null;
260 Calendar today = Calendar.getInstance();
261 Calendar yesterday = Calendar.getInstance();
262 yesterday.add(Calendar.DATE, -1);
263
Patrick Scott7d50a932011-02-04 09:27:26 -0500264 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700265 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800266 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700267
Patrick Scott7d50a932011-02-04 09:27:26 -0500268 // Find out if we will restore any state and remember the tab.
269 final int currentTab =
270 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000271
Patrick Scott7d50a932011-02-04 09:27:26 -0500272 if (currentTab == -1) {
273 // Not able to restore so we go ahead and clear session cookies. We
274 // must do this before trying to login the user as we don't want to
275 // clear any session cookies set during login.
276 CookieManager.getInstance().removeSessionCookie();
277 }
278
279 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings,
280 new Runnable() {
281 @Override public void run() {
282 start(icicle, intent, currentTab, restoreIncognitoTabs);
283 }
284 });
285 }
286
287 private void start(Bundle icicle, Intent intent, int currentTab,
288 boolean restoreIncognitoTabs) {
289 if (currentTab == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700290 final Bundle extra = intent.getExtras();
291 // Create an initial tab.
292 // If the intent is ACTION_VIEW and data is not null, the Browser is
293 // invoked to view the content by another application. In this case,
294 // the tab will be close when exit.
295 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
296
297 String action = intent.getAction();
298 final Tab t = mTabControl.createNewTab(
299 (Intent.ACTION_VIEW.equals(action) &&
300 intent.getData() != null)
301 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
302 .equals(action),
303 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
304 urlData.mUrl, false);
305 addTab(t);
306 setActiveTab(t);
307 WebView webView = t.getWebView();
308 if (extra != null) {
309 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
310 if (scale > 0 && scale <= 1000) {
311 webView.setInitialScale(scale);
312 }
313 }
314
315 if (urlData.isEmpty()) {
316 loadUrl(webView, mSettings.getHomePage());
317 } else {
318 loadUrlDataIn(t, urlData);
319 }
320 } else {
Patrick Scott7d50a932011-02-04 09:27:26 -0500321 mTabControl.restoreState(icicle, currentTab, restoreIncognitoTabs,
322 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800323 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700324 // TabControl.restoreState() will create a new tab even if
325 // restoring the state fails.
326 setActiveTab(mTabControl.getCurrentTab());
327 }
328 // clear up the thumbnail directory, which is no longer used;
329 // ideally this should only be run once after an upgrade from
330 // a previous version of the browser
331 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
332 .listFiles());
333 // Read JavaScript flags if it exists.
334 String jsFlags = getSettings().getJsFlags();
335 if (jsFlags.trim().length() != 0) {
336 getCurrentWebView().setJsFlags(jsFlags);
337 }
John Reck439c9a52010-12-14 10:04:39 -0800338 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
339 bookmarksOrHistoryPicker(false);
340 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700341 }
342
343 void setWebViewFactory(WebViewFactory factory) {
344 mFactory = factory;
345 }
346
Michael Kolb1514bb72010-11-22 09:11:48 -0800347 @Override
348 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700349 return mFactory;
350 }
351
352 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800353 public void onSetWebView(Tab tab, WebView view) {
354 mUi.onSetWebView(tab, view);
355 }
356
357 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800358 public void createSubWindow(Tab tab) {
359 endActionMode();
360 WebView mainView = tab.getWebView();
361 WebView subView = mFactory.createWebView((mainView == null)
362 ? false
363 : mainView.isPrivateBrowsingEnabled());
364 mUi.createSubWindow(tab, subView);
365 }
366
367 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700368 public Activity getActivity() {
369 return mActivity;
370 }
371
372 void setUi(UI ui) {
373 mUi = ui;
374 }
375
376 BrowserSettings getSettings() {
377 return mSettings;
378 }
379
380 IntentHandler getIntentHandler() {
381 return mIntentHandler;
382 }
383
384 @Override
385 public UI getUi() {
386 return mUi;
387 }
388
389 int getMaxTabs() {
390 return mActivity.getResources().getInteger(R.integer.max_tabs);
391 }
392
393 @Override
394 public TabControl getTabControl() {
395 return mTabControl;
396 }
397
Michael Kolb1bf23132010-11-19 12:55:12 -0800398 @Override
399 public List<Tab> getTabs() {
400 return mTabControl.getTabs();
401 }
402
Michael Kolb8233fac2010-10-26 16:08:53 -0700403 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000404 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700405 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000406 // WebIconDatabase needs to be retrieved on the UI thread so that if
407 // it has not been created successfully yet the Handler is started on the
408 // UI thread.
409 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
410 }
411
412 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
413 private WebIconDatabase mDb;
414
415 public RetainIconsOnStartupTask(WebIconDatabase db) {
416 mDb = db;
417 }
418
John Recka00cbbd2010-12-16 12:38:19 -0800419 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000420 protected Void doInBackground(Void... unused) {
421 mDb.open(mActivity.getDir("icons", 0).getPath());
422 Cursor c = null;
423 try {
424 c = Browser.getAllBookmarks(mActivity.getContentResolver());
425 if (c.moveToFirst()) {
426 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
427 do {
428 String url = c.getString(urlIndex);
429 mDb.retainIconForPageUrl(url);
430 } while (c.moveToNext());
431 }
432 } catch (IllegalStateException e) {
433 Log.e(LOGTAG, "retainIconsOnStartup", e);
434 } finally {
435 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700436 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000437
438 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700439 }
440 }
441
442 private void startHandler() {
443 mHandler = new Handler() {
444
445 @Override
446 public void handleMessage(Message msg) {
447 switch (msg.what) {
448 case OPEN_BOOKMARKS:
449 bookmarksOrHistoryPicker(false);
450 break;
451 case FOCUS_NODE_HREF:
452 {
453 String url = (String) msg.getData().get("url");
454 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500455 String src = (String) msg.getData().get("src");
456 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700457 if (TextUtils.isEmpty(url)) {
458 break;
459 }
460 HashMap focusNodeMap = (HashMap) msg.obj;
461 WebView view = (WebView) focusNodeMap.get("webview");
462 // Only apply the action if the top window did not change.
463 if (getCurrentTopWebView() != view) {
464 break;
465 }
466 switch (msg.arg1) {
467 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700468 loadUrlFromContext(getCurrentTopWebView(), url);
469 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500470 case R.id.view_image_context_menu_id:
471 loadUrlFromContext(getCurrentTopWebView(), src);
472 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500473 case R.id.open_newtab_context_menu_id:
474 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800475 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500476 if (newTab != null && newTab != parent) {
477 parent.addChildTab(newTab);
478 }
479 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700480 case R.id.copy_link_context_menu_id:
481 copy(url);
482 break;
483 case R.id.save_link_context_menu_id:
484 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500485 DownloadHandler.onDownloadStartNoStream(
486 mActivity, url, null, null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -0700487 break;
488 }
489 break;
490 }
491
492 case LOAD_URL:
493 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
494 break;
495
496 case STOP_LOAD:
497 stopLoading();
498 break;
499
500 case RELEASE_WAKELOCK:
501 if (mWakeLock.isHeld()) {
502 mWakeLock.release();
503 // if we reach here, Browser should be still in the
504 // background loading after WAKELOCK_TIMEOUT (5-min).
505 // To avoid burning the battery, stop loading.
506 mTabControl.stopAllLoading();
507 }
508 break;
509
510 case UPDATE_BOOKMARK_THUMBNAIL:
511 WebView view = (WebView) msg.obj;
512 if (view != null) {
513 updateScreenshot(view);
514 }
515 break;
516 }
517 }
518 };
519
520 }
521
Michael Kolbba99c5d2010-11-29 14:57:41 -0800522 @Override
523 public void shareCurrentPage() {
524 shareCurrentPage(mTabControl.getCurrentTab());
525 }
526
527 private void shareCurrentPage(Tab tab) {
528 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800529 sharePage(mActivity, tab.getTitle(),
530 tab.getUrl(), tab.getFavicon(),
531 createScreenshot(tab.getWebView(),
532 getDesiredThumbnailWidth(mActivity),
533 getDesiredThumbnailHeight(mActivity)));
534 }
535 }
536
Michael Kolb8233fac2010-10-26 16:08:53 -0700537 /**
538 * Share a page, providing the title, url, favicon, and a screenshot. Uses
539 * an {@link Intent} to launch the Activity chooser.
540 * @param c Context used to launch a new Activity.
541 * @param title Title of the page. Stored in the Intent with
542 * {@link Intent#EXTRA_SUBJECT}
543 * @param url URL of the page. Stored in the Intent with
544 * {@link Intent#EXTRA_TEXT}
545 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
546 * with {@link Browser#EXTRA_SHARE_FAVICON}
547 * @param screenshot Bitmap of a screenshot of the page. Stored in the
548 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
549 */
550 static final void sharePage(Context c, String title, String url,
551 Bitmap favicon, Bitmap screenshot) {
552 Intent send = new Intent(Intent.ACTION_SEND);
553 send.setType("text/plain");
554 send.putExtra(Intent.EXTRA_TEXT, url);
555 send.putExtra(Intent.EXTRA_SUBJECT, title);
556 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
557 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
558 try {
559 c.startActivity(Intent.createChooser(send, c.getString(
560 R.string.choosertitle_sharevia)));
561 } catch(android.content.ActivityNotFoundException ex) {
562 // if no app handles it, do nothing
563 }
564 }
565
566 private void copy(CharSequence text) {
567 ClipboardManager cm = (ClipboardManager) mActivity
568 .getSystemService(Context.CLIPBOARD_SERVICE);
569 cm.setText(text);
570 }
571
572 // lifecycle
573
574 protected void onConfgurationChanged(Configuration config) {
575 mConfigChanged = true;
576 if (mPageDialogsHandler != null) {
577 mPageDialogsHandler.onConfigurationChanged(config);
578 }
579 mUi.onConfigurationChanged(config);
580 }
581
582 @Override
583 public void handleNewIntent(Intent intent) {
584 mIntentHandler.onNewIntent(intent);
585 }
586
587 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800588 if (mUi.isCustomViewShowing()) {
589 hideCustomView();
590 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700591 if (mActivityPaused) {
592 Log.e(LOGTAG, "BrowserActivity is already paused.");
593 return;
594 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700595 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800596 Tab tab = mTabControl.getCurrentTab();
597 if (tab != null) {
598 tab.pause();
599 if (!pauseWebViewTimers(tab)) {
600 mWakeLock.acquire();
601 mHandler.sendMessageDelayed(mHandler
602 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
603 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700604 }
605 mUi.onPause();
606 mNetworkHandler.onPause();
607
608 WebView.disablePlatformNotifications();
609 }
610
611 void onSaveInstanceState(Bundle outState) {
612 // the default implementation requires each view to have an id. As the
613 // browser handles the state itself and it doesn't use id for the views,
614 // don't call the default implementation. Otherwise it will trigger the
615 // warning like this, "couldn't save which view has focus because the
616 // focused view XXX has no id".
617
618 // Save all the tabs
619 mTabControl.saveState(outState);
620 // Save time so that we know how old incognito tabs (if any) are.
621 outState.putSerializable("lastActiveDate", Calendar.getInstance());
622 }
623
624 void onResume() {
625 if (!mActivityPaused) {
626 Log.e(LOGTAG, "BrowserActivity is already resumed.");
627 return;
628 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700629 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800630 Tab current = mTabControl.getCurrentTab();
631 if (current != null) {
632 current.resume();
633 resumeWebViewTimers(current);
634 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700635 if (mWakeLock.isHeld()) {
636 mHandler.removeMessages(RELEASE_WAKELOCK);
637 mWakeLock.release();
638 }
639 mUi.onResume();
640 mNetworkHandler.onResume();
641 WebView.enablePlatformNotifications();
642 }
643
Michael Kolb70976932010-11-30 11:34:01 -0800644 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800645 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800646 * @param tab guaranteed non-null
647 */
648 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700649 boolean inLoad = tab.inPageLoad();
650 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
651 CookieSyncManager.getInstance().startSync();
652 WebView w = tab.getWebView();
653 if (w != null) {
654 w.resumeTimers();
655 }
656 }
657 }
658
Michael Kolb70976932010-11-30 11:34:01 -0800659 /**
660 * Pause all WebView timers using the WebView of the given tab
661 * @param tab
662 * @return true if the timers are paused or tab is null
663 */
664 private boolean pauseWebViewTimers(Tab tab) {
665 if (tab == null) {
666 return true;
667 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700668 CookieSyncManager.getInstance().stopSync();
669 WebView w = getCurrentWebView();
670 if (w != null) {
671 w.pauseTimers();
672 }
673 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700674 }
Michael Kolb70976932010-11-30 11:34:01 -0800675 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700676 }
677
678 void onDestroy() {
679 if (mUploadHandler != null) {
680 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
681 mUploadHandler = null;
682 }
683 if (mTabControl == null) return;
684 mUi.onDestroy();
685 // Remove the current tab and sub window
686 Tab t = mTabControl.getCurrentTab();
687 if (t != null) {
688 dismissSubWindow(t);
689 removeTab(t);
690 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500691 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700692 // Destroy all the tabs
693 mTabControl.destroy();
694 WebIconDatabase.getInstance().close();
695 // Stop watching the default geolocation permissions
696 mSystemAllowGeolocationOrigins.stop();
697 mSystemAllowGeolocationOrigins = null;
698 }
699
700 protected boolean isActivityPaused() {
701 return mActivityPaused;
702 }
703
704 protected void onLowMemory() {
705 mTabControl.freeMemory();
706 }
707
708 @Override
709 public boolean shouldShowErrorConsole() {
710 return mShouldShowErrorConsole;
711 }
712
713 protected void setShouldShowErrorConsole(boolean show) {
714 if (show == mShouldShowErrorConsole) {
715 // Nothing to do.
716 return;
717 }
718 mShouldShowErrorConsole = show;
719 Tab t = mTabControl.getCurrentTab();
720 if (t == null) {
721 // There is no current tab so we cannot toggle the error console
722 return;
723 }
724 mUi.setShouldShowErrorConsole(t, show);
725 }
726
727 @Override
728 public void stopLoading() {
729 mLoadStopped = true;
730 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700731 WebView w = getCurrentTopWebView();
732 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700733 mUi.onPageStopped(tab);
734 }
735
736 boolean didUserStopLoading() {
737 return mLoadStopped;
738 }
739
740 // WebViewController
741
742 @Override
John Reck324d4402011-01-11 16:56:42 -0800743 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700744
745 // We've started to load a new page. If there was a pending message
746 // to save a screenshot then we will now take the new page and save
747 // an incorrect screenshot. Therefore, remove any pending thumbnail
748 // messages from the queue.
749 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
750 view);
751
752 // reset sync timer to avoid sync starts during loading a page
753 CookieSyncManager.getInstance().resetSync();
754
755 if (!mNetworkHandler.isNetworkUp()) {
756 view.setNetworkAvailable(false);
757 }
758
759 // when BrowserActivity just starts, onPageStarted may be called before
760 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
761 // to start the timer. As we won't switch tabs while an activity is in
762 // pause state, we can ensure calling resume and pause in pair.
763 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800764 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700765 }
766 mLoadStopped = false;
767 if (!mNetworkHandler.isNetworkUp()) {
768 mNetworkHandler.createAndShowNetworkDialog();
769 }
770 endActionMode();
771
John Reck30c714c2010-12-16 17:30:34 -0800772 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700773
John Reck324d4402011-01-11 16:56:42 -0800774 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700775 // update the bookmark database for favicon
776 maybeUpdateFavicon(tab, null, url, favicon);
777
778 Performance.tracePageStart(url);
779
780 // Performance probe
781 if (false) {
782 Performance.onPageStarted();
783 }
784
785 }
786
787 @Override
John Reck324d4402011-01-11 16:56:42 -0800788 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800789 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800790 if (!tab.isPrivateBrowsingEnabled()
791 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700792 if (tab.inForeground() && !didUserStopLoading()
793 || !tab.inForeground()) {
794 // Only update the bookmark screenshot if the user did not
795 // cancel the load early.
796 mHandler.sendMessageDelayed(mHandler.obtainMessage(
797 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab.getWebView()),
798 500);
799 }
800 }
801 // pause the WebView timer and release the wake lock if it is finished
802 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800803 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700804 if (mWakeLock.isHeld()) {
805 mHandler.removeMessages(RELEASE_WAKELOCK);
806 mWakeLock.release();
807 }
808 }
809 // Performance probe
810 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800811 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700812 }
813
814 Performance.tracePageFinished();
815 }
816
817 @Override
John Reck30c714c2010-12-16 17:30:34 -0800818 public void onProgressChanged(Tab tab) {
819 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700820
821 if (newProgress == 100) {
822 CookieSyncManager.getInstance().sync();
823 // onProgressChanged() may continue to be called after the main
824 // frame has finished loading, as any remaining sub frames continue
825 // to load. We'll only get called once though with newProgress as
826 // 100 when everything is loaded. (onPageFinished is called once
827 // when the main frame completes loading regardless of the state of
828 // any sub frames so calls to onProgressChanges may continue after
829 // onPageFinished has executed)
830 if (mInLoad) {
831 mInLoad = false;
832 updateInLoadMenuItems(mCachedMenu);
833 }
834 } else {
835 if (!mInLoad) {
836 // onPageFinished may have already been called but a subframe is
837 // still loading and updating the progress. Reset mInLoad and
838 // update the menu items.
839 mInLoad = true;
840 updateInLoadMenuItems(mCachedMenu);
841 }
842 }
John Reck30c714c2010-12-16 17:30:34 -0800843 mUi.onProgressChanged(tab);
844 }
845
846 @Override
847 public void onUpdatedLockIcon(Tab tab) {
848 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700849 }
850
851 @Override
852 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800853 mUi.onTabDataChanged(tab);
854 final String pageUrl = tab.getUrl();
John Reck324d4402011-01-11 16:56:42 -0800855 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700856 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
857 return;
858 }
859 // Update the title in the history database if not in private browsing mode
860 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800861 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700862 }
863 }
864
865 @Override
866 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800867 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700868 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
869 }
870
871 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800872 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
873 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700874 }
875
876 @Override
877 public boolean shouldOverrideKeyEvent(KeyEvent event) {
878 if (mMenuIsDown) {
879 // only check shortcut key when MENU is held
880 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
881 event);
882 } else {
883 return false;
884 }
885 }
886
887 @Override
888 public void onUnhandledKeyEvent(KeyEvent event) {
889 if (!isActivityPaused()) {
890 if (event.getAction() == KeyEvent.ACTION_DOWN) {
891 mActivity.onKeyDown(event.getKeyCode(), event);
892 } else {
893 mActivity.onKeyUp(event.getKeyCode(), event);
894 }
895 }
896 }
897
898 @Override
John Reck324d4402011-01-11 16:56:42 -0800899 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700900 // Don't save anything in private browsing mode
901 if (tab.isPrivateBrowsingEnabled()) return;
John Reck324d4402011-01-11 16:56:42 -0800902 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700903
John Reck324d4402011-01-11 16:56:42 -0800904 if (TextUtils.isEmpty(url)
905 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700906 return;
907 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800908 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700909 WebIconDatabase.getInstance().retainIconForPageUrl(url);
910 }
911
912 @Override
913 public void getVisitedHistory(final ValueCallback<String[]> callback) {
914 AsyncTask<Void, Void, String[]> task =
915 new AsyncTask<Void, Void, String[]>() {
916 @Override
917 public String[] doInBackground(Void... unused) {
918 return Browser.getVisitedHistory(mActivity.getContentResolver());
919 }
920 @Override
921 public void onPostExecute(String[] result) {
922 callback.onReceiveValue(result);
923 }
924 };
925 task.execute();
926 }
927
928 @Override
929 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
930 final HttpAuthHandler handler, final String host,
931 final String realm) {
932 String username = null;
933 String password = null;
934
935 boolean reuseHttpAuthUsernamePassword
936 = handler.useHttpAuthUsernamePassword();
937
938 if (reuseHttpAuthUsernamePassword && view != null) {
939 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
940 if (credentials != null && credentials.length == 2) {
941 username = credentials[0];
942 password = credentials[1];
943 }
944 }
945
946 if (username != null && password != null) {
947 handler.proceed(username, password);
948 } else {
949 if (tab.inForeground()) {
950 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
951 } else {
952 handler.cancel();
953 }
954 }
955 }
956
957 @Override
958 public void onDownloadStart(Tab tab, String url, String userAgent,
959 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500960 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
961 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700962 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
963 // This Tab was opened for the sole purpose of downloading a
964 // file. Remove it.
965 if (tab == mTabControl.getCurrentTab()) {
966 // In this case, the Tab is still on top.
967 goBackOnePageOrQuit();
968 } else {
969 // In this case, it is not.
970 closeTab(tab);
971 }
972 }
973 }
974
975 @Override
976 public Bitmap getDefaultVideoPoster() {
977 return mUi.getDefaultVideoPoster();
978 }
979
980 @Override
981 public View getVideoLoadingProgressView() {
982 return mUi.getVideoLoadingProgressView();
983 }
984
985 @Override
986 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
987 SslError error) {
988 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
989 }
990
991 // helper method
992
993 /*
994 * Update the favorites icon if the private browsing isn't enabled and the
995 * icon is valid.
996 */
997 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
998 final String url, Bitmap favicon) {
999 if (favicon == null) {
1000 return;
1001 }
1002 if (!tab.isPrivateBrowsingEnabled()) {
1003 Bookmarks.updateFavicon(mActivity
1004 .getContentResolver(), originalUrl, url, favicon);
1005 }
1006 }
1007
Leon Scroggins4cd97792010-12-03 15:31:56 -05001008 @Override
1009 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001010 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001011 mUi.bookmarkedStatusHasChanged(tab);
1012 }
1013
Michael Kolb8233fac2010-10-26 16:08:53 -07001014 // end WebViewController
1015
1016 protected void pageUp() {
1017 getCurrentTopWebView().pageUp(false);
1018 }
1019
1020 protected void pageDown() {
1021 getCurrentTopWebView().pageDown(false);
1022 }
1023
1024 // callback from phone title bar
1025 public void editUrl() {
1026 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1027 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1028 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1029 null, false);
1030 }
1031
Michael Kolbcfa3af52010-12-14 10:36:11 -08001032 public void startVoiceSearch() {
1033 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1034 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1035 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1036 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1037 mActivity.getComponentName().flattenToString());
1038 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001039 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001040 mActivity.startActivity(intent);
1041 }
1042
Michael Kolb8233fac2010-10-26 16:08:53 -07001043 public void activateVoiceSearchMode(String title) {
1044 mUi.showVoiceTitleBar(title);
1045 }
1046
1047 public void revertVoiceSearchMode(Tab tab) {
1048 mUi.revertVoiceTitleBar(tab);
1049 }
1050
1051 public void showCustomView(Tab tab, View view,
1052 WebChromeClient.CustomViewCallback callback) {
1053 if (tab.inForeground()) {
1054 if (mUi.isCustomViewShowing()) {
1055 callback.onCustomViewHidden();
1056 return;
1057 }
1058 mUi.showCustomView(view, callback);
1059 // Save the menu state and set it to empty while the custom
1060 // view is showing.
1061 mOldMenuState = mMenuState;
1062 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001063 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001064 }
1065 }
1066
1067 @Override
1068 public void hideCustomView() {
1069 if (mUi.isCustomViewShowing()) {
1070 mUi.onHideCustomView();
1071 // Reset the old menu state.
1072 mMenuState = mOldMenuState;
1073 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001074 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001075 }
1076 }
1077
1078 protected void onActivityResult(int requestCode, int resultCode,
1079 Intent intent) {
1080 if (getCurrentTopWebView() == null) return;
1081 switch (requestCode) {
1082 case PREFERENCES_PAGE:
1083 if (resultCode == Activity.RESULT_OK && intent != null) {
1084 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1085 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1086 mTabControl.removeParentChildRelationShips();
1087 }
1088 }
1089 break;
1090 case FILE_SELECTED:
1091 // Choose a file from the file picker.
1092 if (null == mUploadHandler) break;
1093 mUploadHandler.onResult(resultCode, intent);
1094 mUploadHandler = null;
1095 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001096 case AUTOFILL_SETUP:
1097 // Determine whether a profile was actually set up or not
1098 // and if so, send the message back to the WebTextView to
1099 // fill the form with the new profile.
1100 if (getSettings().getAutoFillProfile() != null) {
1101 mAutoFillSetupMessage.sendToTarget();
1102 mAutoFillSetupMessage = null;
1103 }
1104 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001105 default:
1106 break;
1107 }
1108 getCurrentTopWebView().requestFocus();
1109 }
1110
1111 /**
1112 * Open the Go page.
1113 * @param startWithHistory If true, open starting on the history tab.
1114 * Otherwise, start with the bookmarks tab.
1115 */
1116 @Override
1117 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1118 if (mTabControl.getCurrentWebView() == null) {
1119 return;
1120 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001121 // clear action mode
1122 if (isInCustomActionMode()) {
1123 endActionMode();
1124 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001125 Bundle extras = new Bundle();
1126 // Disable opening in a new window if we have maxed out the windows
1127 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1128 !mTabControl.canCreateNewTab());
1129 mUi.showComboView(startWithHistory, extras);
1130 }
1131
1132 // combo view callbacks
1133
1134 /**
1135 * callback from ComboPage when clear history is requested
1136 */
1137 public void onRemoveParentChildRelationships() {
1138 mTabControl.removeParentChildRelationShips();
1139 }
1140
1141 /**
1142 * callback from ComboPage when bookmark/history selection
1143 */
1144 @Override
1145 public void onUrlSelected(String url, boolean newTab) {
1146 removeComboView();
1147 if (!TextUtils.isEmpty(url)) {
1148 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001149 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001150 } else {
1151 final Tab currentTab = mTabControl.getCurrentTab();
1152 dismissSubWindow(currentTab);
1153 loadUrl(getCurrentTopWebView(), url);
1154 }
1155 }
1156 }
1157
1158 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001159 * dismiss the ComboPage
1160 */
1161 @Override
1162 public void removeComboView() {
1163 mUi.hideComboView();
1164 }
1165
1166 // active tabs page handling
1167
1168 protected void showActiveTabsPage() {
1169 mMenuState = EMPTY_MENU;
1170 mUi.showActiveTabsPage();
1171 }
1172
1173 /**
1174 * Remove the active tabs page.
1175 * @param needToAttach If true, the active tabs page did not attach a tab
1176 * to the content view, so we need to do that here.
1177 */
1178 @Override
1179 public void removeActiveTabsPage(boolean needToAttach) {
1180 mMenuState = R.id.MAIN_MENU;
1181 mUi.removeActiveTabsPage();
1182 if (needToAttach) {
1183 setActiveTab(mTabControl.getCurrentTab());
1184 }
1185 getCurrentTopWebView().requestFocus();
1186 }
1187
1188 // key handling
1189 protected void onBackKey() {
1190 if (!mUi.onBackKey()) {
1191 WebView subwindow = mTabControl.getCurrentSubWindow();
1192 if (subwindow != null) {
1193 if (subwindow.canGoBack()) {
1194 subwindow.goBack();
1195 } else {
1196 dismissSubWindow(mTabControl.getCurrentTab());
1197 }
1198 } else {
1199 goBackOnePageOrQuit();
1200 }
1201 }
1202 }
1203
1204 // menu handling and state
1205 // TODO: maybe put into separate handler
1206
1207 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001208 if (mOptionsMenuHandler != null) {
1209 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1210 }
1211
John Reckd73c5a22010-12-22 10:22:50 -08001212 if (mMenuState == EMPTY_MENU) {
1213 return false;
1214 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001215 MenuInflater inflater = mActivity.getMenuInflater();
1216 inflater.inflate(R.menu.browser, menu);
1217 updateInLoadMenuItems(menu);
1218 // hold on to the menu reference here; it is used by the page callbacks
1219 // to update the menu based on loading state
1220 mCachedMenu = menu;
1221 return true;
1222 }
1223
1224 protected void onCreateContextMenu(ContextMenu menu, View v,
1225 ContextMenuInfo menuInfo) {
1226 if (v instanceof TitleBarBase) {
1227 return;
1228 }
1229 if (!(v instanceof WebView)) {
1230 return;
1231 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001232 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001233 WebView.HitTestResult result = webview.getHitTestResult();
1234 if (result == null) {
1235 return;
1236 }
1237
1238 int type = result.getType();
1239 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1240 Log.w(LOGTAG,
1241 "We should not show context menu when nothing is touched");
1242 return;
1243 }
1244 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1245 // let TextView handles context menu
1246 return;
1247 }
1248
1249 // Note, http://b/issue?id=1106666 is requesting that
1250 // an inflated menu can be used again. This is not available
1251 // yet, so inflate each time (yuk!)
1252 MenuInflater inflater = mActivity.getMenuInflater();
1253 inflater.inflate(R.menu.browsercontext, menu);
1254
1255 // Show the correct menu group
1256 final String extra = result.getExtra();
1257 menu.setGroupVisible(R.id.PHONE_MENU,
1258 type == WebView.HitTestResult.PHONE_TYPE);
1259 menu.setGroupVisible(R.id.EMAIL_MENU,
1260 type == WebView.HitTestResult.EMAIL_TYPE);
1261 menu.setGroupVisible(R.id.GEO_MENU,
1262 type == WebView.HitTestResult.GEO_TYPE);
1263 menu.setGroupVisible(R.id.IMAGE_MENU,
1264 type == WebView.HitTestResult.IMAGE_TYPE
1265 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1266 menu.setGroupVisible(R.id.ANCHOR_MENU,
1267 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1268 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001269 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1270 || type == WebView.HitTestResult.PHONE_TYPE
1271 || type == WebView.HitTestResult.EMAIL_TYPE
1272 || type == WebView.HitTestResult.GEO_TYPE;
1273 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1274 if (hitText) {
1275 menu.findItem(R.id.select_text_menu_id)
1276 .setOnMenuItemClickListener(new SelectText(webview));
1277 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001278 // Setup custom handling depending on the type
1279 switch (type) {
1280 case WebView.HitTestResult.PHONE_TYPE:
1281 menu.setHeaderTitle(Uri.decode(extra));
1282 menu.findItem(R.id.dial_context_menu_id).setIntent(
1283 new Intent(Intent.ACTION_VIEW, Uri
1284 .parse(WebView.SCHEME_TEL + extra)));
1285 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1286 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1287 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1288 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1289 addIntent);
1290 menu.findItem(R.id.copy_phone_context_menu_id)
1291 .setOnMenuItemClickListener(
1292 new Copy(extra));
1293 break;
1294
1295 case WebView.HitTestResult.EMAIL_TYPE:
1296 menu.setHeaderTitle(extra);
1297 menu.findItem(R.id.email_context_menu_id).setIntent(
1298 new Intent(Intent.ACTION_VIEW, Uri
1299 .parse(WebView.SCHEME_MAILTO + extra)));
1300 menu.findItem(R.id.copy_mail_context_menu_id)
1301 .setOnMenuItemClickListener(
1302 new Copy(extra));
1303 break;
1304
1305 case WebView.HitTestResult.GEO_TYPE:
1306 menu.setHeaderTitle(extra);
1307 menu.findItem(R.id.map_context_menu_id).setIntent(
1308 new Intent(Intent.ACTION_VIEW, Uri
1309 .parse(WebView.SCHEME_GEO
1310 + URLEncoder.encode(extra))));
1311 menu.findItem(R.id.copy_geo_context_menu_id)
1312 .setOnMenuItemClickListener(
1313 new Copy(extra));
1314 break;
1315
1316 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1317 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001318 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001319 // decide whether to show the open link in new tab option
1320 boolean showNewTab = mTabControl.canCreateNewTab();
1321 MenuItem newTabItem
1322 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001323 newTabItem.setTitle(
1324 BrowserSettings.getInstance().openInBackground()
1325 ? R.string.contextmenu_openlink_newwindow_background
1326 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001327 newTabItem.setVisible(showNewTab);
1328 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001329 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1330 newTabItem.setOnMenuItemClickListener(
1331 new MenuItem.OnMenuItemClickListener() {
1332 @Override
1333 public boolean onMenuItemClick(MenuItem item) {
1334 final HashMap<String, WebView> hrefMap =
1335 new HashMap<String, WebView>();
1336 hrefMap.put("webview", webview);
1337 final Message msg = mHandler.obtainMessage(
1338 FOCUS_NODE_HREF,
1339 R.id.open_newtab_context_menu_id,
1340 0, hrefMap);
1341 webview.requestFocusNodeHref(msg);
1342 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001343 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001344 });
1345 } else {
1346 newTabItem.setOnMenuItemClickListener(
1347 new MenuItem.OnMenuItemClickListener() {
1348 @Override
1349 public boolean onMenuItemClick(MenuItem item) {
1350 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001351 final Tab newTab = openTab(parent,
1352 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001353 if (newTab != parent) {
1354 parent.addChildTab(newTab);
1355 }
1356 return true;
1357 }
1358 });
1359 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001360 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001361 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1362 break;
1363 }
1364 // otherwise fall through to handle image part
1365 case WebView.HitTestResult.IMAGE_TYPE:
1366 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1367 menu.setHeaderTitle(extra);
1368 }
1369 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1370 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1371 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001372 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001373 menu.findItem(R.id.set_wallpaper_context_menu_id).
1374 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1375 extra));
1376 break;
1377
1378 default:
1379 Log.w(LOGTAG, "We should not get here.");
1380 break;
1381 }
1382 //update the ui
1383 mUi.onContextMenuCreated(menu);
1384 }
1385
1386 /**
1387 * As the menu can be open when loading state changes
1388 * we must manually update the state of the stop/reload menu
1389 * item
1390 */
1391 private void updateInLoadMenuItems(Menu menu) {
1392 if (menu == null) {
1393 return;
1394 }
1395 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1396 MenuItem src = mInLoad ?
1397 menu.findItem(R.id.stop_menu_id):
1398 menu.findItem(R.id.reload_menu_id);
1399 if (src != null) {
1400 dest.setIcon(src.getIcon());
1401 dest.setTitle(src.getTitle());
1402 }
1403 }
1404
John Reckb3417f02011-01-14 11:01:05 -08001405 boolean onPrepareOptionsMenu(Menu menu) {
1406 if (mOptionsMenuHandler != null) {
1407 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1408 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001409 // This happens when the user begins to hold down the menu key, so
1410 // allow them to chord to get a shortcut.
1411 mCanChord = true;
1412 // Note: setVisible will decide whether an item is visible; while
1413 // setEnabled() will decide whether an item is enabled, which also means
1414 // whether the matching shortcut key will function.
1415 switch (mMenuState) {
1416 case EMPTY_MENU:
1417 if (mCurrentMenuState != mMenuState) {
1418 menu.setGroupVisible(R.id.MAIN_MENU, false);
1419 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1420 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1421 }
1422 break;
1423 default:
1424 if (mCurrentMenuState != mMenuState) {
1425 menu.setGroupVisible(R.id.MAIN_MENU, true);
1426 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1427 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1428 }
1429 final WebView w = getCurrentTopWebView();
1430 boolean canGoBack = false;
1431 boolean canGoForward = false;
1432 boolean isHome = false;
1433 if (w != null) {
1434 canGoBack = w.canGoBack();
1435 canGoForward = w.canGoForward();
1436 isHome = mSettings.getHomePage().equals(w.getUrl());
1437 }
1438 final MenuItem back = menu.findItem(R.id.back_menu_id);
1439 back.setEnabled(canGoBack);
1440
1441 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1442 home.setEnabled(!isHome);
1443
1444 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1445 forward.setEnabled(canGoForward);
1446
1447 // decide whether to show the share link option
1448 PackageManager pm = mActivity.getPackageManager();
1449 Intent send = new Intent(Intent.ACTION_SEND);
1450 send.setType("text/plain");
1451 ResolveInfo ri = pm.resolveActivity(send,
1452 PackageManager.MATCH_DEFAULT_ONLY);
1453 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1454
1455 boolean isNavDump = mSettings.isNavDump();
1456 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1457 nav.setVisible(isNavDump);
1458 nav.setEnabled(isNavDump);
1459
1460 boolean showDebugSettings = mSettings.showDebugSettings();
1461 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1462 counter.setVisible(showDebugSettings);
1463 counter.setEnabled(showDebugSettings);
1464
John Reckb3417f02011-01-14 11:01:05 -08001465 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1466 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001467
1468 break;
1469 }
1470 mCurrentMenuState = mMenuState;
1471 return true;
1472 }
1473
1474 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001475 if (mOptionsMenuHandler != null &&
1476 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1477 return true;
1478 }
1479
Michael Kolb8233fac2010-10-26 16:08:53 -07001480 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1481 // menu remains active, so ensure comboview is dismissed
1482 // if main menu option is selected
1483 removeComboView();
1484 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001485 if (!mCanChord) {
1486 // The user has already fired a shortcut with this hold down of the
1487 // menu key.
1488 return false;
1489 }
1490 if (null == getCurrentTopWebView()) {
1491 return false;
1492 }
1493 if (mMenuIsDown) {
1494 // The shortcut action consumes the MENU. Even if it is still down,
1495 // it won't trigger the next shortcut action. In the case of the
1496 // shortcut action triggering a new activity, like Bookmarks, we
1497 // won't get onKeyUp for MENU. So it is important to reset it here.
1498 mMenuIsDown = false;
1499 }
1500 switch (item.getItemId()) {
1501 // -- Main menu
1502 case R.id.new_tab_menu_id:
1503 openTabToHomePage();
1504 break;
1505
1506 case R.id.incognito_menu_id:
1507 openIncognitoTab();
1508 break;
1509
1510 case R.id.goto_menu_id:
1511 editUrl();
1512 break;
1513
1514 case R.id.bookmarks_menu_id:
1515 bookmarksOrHistoryPicker(false);
1516 break;
1517
1518 case R.id.active_tabs_menu_id:
1519 showActiveTabsPage();
1520 break;
1521
1522 case R.id.add_bookmark_menu_id:
1523 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1524 break;
1525
1526 case R.id.stop_reload_menu_id:
1527 if (mInLoad) {
1528 stopLoading();
1529 } else {
1530 getCurrentTopWebView().reload();
1531 }
1532 break;
1533
1534 case R.id.back_menu_id:
1535 getCurrentTopWebView().goBack();
1536 break;
1537
1538 case R.id.forward_menu_id:
1539 getCurrentTopWebView().goForward();
1540 break;
1541
1542 case R.id.close_menu_id:
1543 // Close the subwindow if it exists.
1544 if (mTabControl.getCurrentSubWindow() != null) {
1545 dismissSubWindow(mTabControl.getCurrentTab());
1546 break;
1547 }
1548 closeCurrentTab();
1549 break;
1550
1551 case R.id.homepage_menu_id:
1552 Tab current = mTabControl.getCurrentTab();
1553 if (current != null) {
1554 dismissSubWindow(current);
1555 loadUrl(current.getWebView(), mSettings.getHomePage());
1556 }
1557 break;
1558
1559 case R.id.preferences_menu_id:
1560 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1561 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1562 getCurrentTopWebView().getUrl());
1563 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1564 break;
1565
1566 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001567 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001568 break;
1569
1570 case R.id.page_info_menu_id:
1571 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1572 false);
1573 break;
1574
1575 case R.id.classic_history_menu_id:
1576 bookmarksOrHistoryPicker(true);
1577 break;
1578
1579 case R.id.title_bar_share_page_url:
1580 case R.id.share_page_menu_id:
1581 Tab currentTab = mTabControl.getCurrentTab();
1582 if (null == currentTab) {
1583 mCanChord = false;
1584 return false;
1585 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001586 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001587 break;
1588
1589 case R.id.dump_nav_menu_id:
1590 getCurrentTopWebView().debugDump();
1591 break;
1592
1593 case R.id.dump_counters_menu_id:
1594 getCurrentTopWebView().dumpV8Counters();
1595 break;
1596
1597 case R.id.zoom_in_menu_id:
1598 getCurrentTopWebView().zoomIn();
1599 break;
1600
1601 case R.id.zoom_out_menu_id:
1602 getCurrentTopWebView().zoomOut();
1603 break;
1604
1605 case R.id.view_downloads_menu_id:
1606 viewDownloads();
1607 break;
1608
1609 case R.id.window_one_menu_id:
1610 case R.id.window_two_menu_id:
1611 case R.id.window_three_menu_id:
1612 case R.id.window_four_menu_id:
1613 case R.id.window_five_menu_id:
1614 case R.id.window_six_menu_id:
1615 case R.id.window_seven_menu_id:
1616 case R.id.window_eight_menu_id:
1617 {
1618 int menuid = item.getItemId();
1619 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1620 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1621 Tab desiredTab = mTabControl.getTab(id);
1622 if (desiredTab != null &&
1623 desiredTab != mTabControl.getCurrentTab()) {
1624 switchToTab(id);
1625 }
1626 break;
1627 }
1628 }
1629 }
1630 break;
1631
1632 default:
1633 return false;
1634 }
1635 mCanChord = false;
1636 return true;
1637 }
1638
1639 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001640 // Let the History and Bookmark fragments handle menus they created.
1641 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1642 return false;
1643 }
1644
Michael Kolb8233fac2010-10-26 16:08:53 -07001645 // chording is not an issue with context menus, but we use the same
1646 // options selector, so set mCanChord to true so we can access them.
1647 mCanChord = true;
1648 int id = item.getItemId();
1649 boolean result = true;
1650 switch (id) {
1651 // For the context menu from the title bar
1652 case R.id.title_bar_copy_page_url:
1653 Tab currentTab = mTabControl.getCurrentTab();
1654 if (null == currentTab) {
1655 result = false;
1656 break;
1657 }
1658 WebView mainView = currentTab.getWebView();
1659 if (null == mainView) {
1660 result = false;
1661 break;
1662 }
1663 copy(mainView.getUrl());
1664 break;
1665 // -- Browser context menu
1666 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001667 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001668 case R.id.copy_link_context_menu_id:
1669 final WebView webView = getCurrentTopWebView();
1670 if (null == webView) {
1671 result = false;
1672 break;
1673 }
1674 final HashMap<String, WebView> hrefMap =
1675 new HashMap<String, WebView>();
1676 hrefMap.put("webview", webView);
1677 final Message msg = mHandler.obtainMessage(
1678 FOCUS_NODE_HREF, id, 0, hrefMap);
1679 webView.requestFocusNodeHref(msg);
1680 break;
1681
1682 default:
1683 // For other context menus
1684 result = onOptionsItemSelected(item);
1685 }
1686 mCanChord = false;
1687 return result;
1688 }
1689
1690 /**
1691 * support programmatically opening the context menu
1692 */
1693 public void openContextMenu(View view) {
1694 mActivity.openContextMenu(view);
1695 }
1696
1697 /**
1698 * programmatically open the options menu
1699 */
1700 public void openOptionsMenu() {
1701 mActivity.openOptionsMenu();
1702 }
1703
1704 public boolean onMenuOpened(int featureId, Menu menu) {
1705 if (mOptionsMenuOpen) {
1706 if (mConfigChanged) {
1707 // We do not need to make any changes to the state of the
1708 // title bar, since the only thing that happened was a
1709 // change in orientation
1710 mConfigChanged = false;
1711 } else {
1712 if (!mExtendedMenuOpen) {
1713 mExtendedMenuOpen = true;
1714 mUi.onExtendedMenuOpened();
1715 } else {
1716 // Switching the menu back to icon view, so show the
1717 // title bar once again.
1718 mExtendedMenuOpen = false;
1719 mUi.onExtendedMenuClosed(mInLoad);
1720 mUi.onOptionsMenuOpened();
1721 }
1722 }
1723 } else {
1724 // The options menu is closed, so open it, and show the title
1725 mOptionsMenuOpen = true;
1726 mConfigChanged = false;
1727 mExtendedMenuOpen = false;
1728 mUi.onOptionsMenuOpened();
1729 }
1730 return true;
1731 }
1732
1733 public void onOptionsMenuClosed(Menu menu) {
1734 mOptionsMenuOpen = false;
1735 mUi.onOptionsMenuClosed(mInLoad);
1736 }
1737
1738 public void onContextMenuClosed(Menu menu) {
1739 mUi.onContextMenuClosed(menu, mInLoad);
1740 }
1741
1742 // Helper method for getting the top window.
1743 @Override
1744 public WebView getCurrentTopWebView() {
1745 return mTabControl.getCurrentTopWebView();
1746 }
1747
1748 @Override
1749 public WebView getCurrentWebView() {
1750 return mTabControl.getCurrentWebView();
1751 }
1752
1753 /*
1754 * This method is called as a result of the user selecting the options
1755 * menu to see the download window. It shows the download window on top of
1756 * the current window.
1757 */
1758 void viewDownloads() {
1759 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1760 mActivity.startActivity(intent);
1761 }
1762
1763 // action mode
1764
1765 void onActionModeStarted(ActionMode mode) {
1766 mUi.onActionModeStarted(mode);
1767 mActionMode = mode;
1768 }
1769
1770 /*
1771 * True if a custom ActionMode (i.e. find or select) is in use.
1772 */
1773 @Override
1774 public boolean isInCustomActionMode() {
1775 return mActionMode != null;
1776 }
1777
1778 /*
1779 * End the current ActionMode.
1780 */
1781 @Override
1782 public void endActionMode() {
1783 if (mActionMode != null) {
1784 mActionMode.finish();
1785 }
1786 }
1787
1788 /*
1789 * Called by find and select when they are finished. Replace title bars
1790 * as necessary.
1791 */
1792 public void onActionModeFinished(ActionMode mode) {
1793 if (!isInCustomActionMode()) return;
1794 mUi.onActionModeFinished(mInLoad);
1795 mActionMode = null;
1796 }
1797
1798 boolean isInLoad() {
1799 return mInLoad;
1800 }
1801
1802 // bookmark handling
1803
1804 /**
1805 * add the current page as a bookmark to the given folder id
1806 * @param folderId use -1 for the default folder
1807 */
1808 @Override
1809 public void bookmarkCurrentPage(long folderId) {
1810 Intent i = new Intent(mActivity,
1811 AddBookmarkPage.class);
1812 WebView w = getCurrentTopWebView();
1813 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1814 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1815 String touchIconUrl = w.getTouchIconUrl();
1816 if (touchIconUrl != null) {
1817 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1818 WebSettings settings = w.getSettings();
1819 if (settings != null) {
1820 i.putExtra(AddBookmarkPage.USER_AGENT,
1821 settings.getUserAgentString());
1822 }
1823 }
1824 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1825 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1826 getDesiredThumbnailHeight(mActivity)));
1827 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1828 i.putExtra(BrowserContract.Bookmarks.PARENT,
1829 folderId);
1830 // Put the dialog at the upper right of the screen, covering the
1831 // star on the title bar.
1832 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1833 mActivity.startActivity(i);
1834 }
1835
1836 // file chooser
1837 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1838 mUploadHandler = new UploadHandler(this);
1839 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1840 }
1841
1842 // thumbnails
1843
1844 /**
1845 * Return the desired width for thumbnail screenshots, which are stored in
1846 * the database, and used on the bookmarks screen.
1847 * @param context Context for finding out the density of the screen.
1848 * @return desired width for thumbnail screenshot.
1849 */
1850 static int getDesiredThumbnailWidth(Context context) {
1851 return context.getResources().getDimensionPixelOffset(
1852 R.dimen.bookmarkThumbnailWidth);
1853 }
1854
1855 /**
1856 * Return the desired height for thumbnail screenshots, which are stored in
1857 * the database, and used on the bookmarks screen.
1858 * @param context Context for finding out the density of the screen.
1859 * @return desired height for thumbnail screenshot.
1860 */
1861 static int getDesiredThumbnailHeight(Context context) {
1862 return context.getResources().getDimensionPixelOffset(
1863 R.dimen.bookmarkThumbnailHeight);
1864 }
1865
1866 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001867 // We render to a bitmap 2x the desired size so that we can then
1868 // re-scale it with filtering since canvas.scale doesn't filter
1869 // This helps reduce aliasing at the cost of being slightly blurry
1870 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001871 Picture thumbnail = view.capturePicture();
1872 if (thumbnail == null) {
1873 return null;
1874 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001875 width *= filter_scale;
1876 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001877 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1878 Canvas canvas = new Canvas(bm);
1879 // May need to tweak these values to determine what is the
1880 // best scale factor
1881 int thumbnailWidth = thumbnail.getWidth();
1882 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001883 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001884 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001885 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001886 } else {
1887 return null;
1888 }
John Reckfe49ab42010-11-16 17:09:37 -08001889
Michael Kolb8233fac2010-10-26 16:08:53 -07001890 if (view.getWidth() > view.getHeight() &&
1891 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1892 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001893 // than the height of the view, center the thumnail and crop the sides
1894 scaleFactor = (float) height / (float)thumbnailHeight;
1895 float wx = (thumbnailWidth * scaleFactor) - width;
1896 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001897 }
1898
John Reckfe49ab42010-11-16 17:09:37 -08001899 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001900
1901 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001902 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1903 height / filter_scale, true);
1904 bm.recycle();
1905 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001906 }
1907
1908 private void updateScreenshot(WebView view) {
1909 // If this is a bookmarked site, add a screenshot to the database.
1910 // FIXME: When should we update? Every time?
1911 // FIXME: Would like to make sure there is actually something to
1912 // draw, but the API for that (WebViewCore.pictureReady()) is not
1913 // currently accessible here.
1914
1915 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1916 getDesiredThumbnailHeight(mActivity));
1917 if (bm == null) {
1918 return;
1919 }
1920
1921 final ContentResolver cr = mActivity.getContentResolver();
1922 final String url = view.getUrl();
1923 final String originalUrl = view.getOriginalUrl();
1924
John Recka00cbbd2010-12-16 12:38:19 -08001925 // Only update thumbnails for web urls (http(s)://), not for
1926 // about:, javascript:, data:, etc...
John Reck9d038482011-01-04 17:02:09 -08001927 if (url != null && Patterns.WEB_URL.matcher(url).matches()) {
John Recka00cbbd2010-12-16 12:38:19 -08001928 new AsyncTask<Void, Void, Void>() {
1929 @Override
1930 protected Void doInBackground(Void... unused) {
1931 Cursor cursor = null;
1932 try {
1933 // TODO: Clean this up
1934 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1935 if (cursor != null && cursor.moveToFirst()) {
1936 final ByteArrayOutputStream os =
1937 new ByteArrayOutputStream();
1938 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07001939
John Recka00cbbd2010-12-16 12:38:19 -08001940 ContentValues values = new ContentValues();
1941 values.put(Images.THUMBNAIL, os.toByteArray());
1942 values.put(Images.URL, cursor.getString(0));
Michael Kolb8233fac2010-10-26 16:08:53 -07001943
John Recka00cbbd2010-12-16 12:38:19 -08001944 do {
1945 cr.update(Images.CONTENT_URI, values, null, null);
1946 } while (cursor.moveToNext());
1947 }
1948 } catch (IllegalStateException e) {
1949 // Ignore
1950 } finally {
1951 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07001952 }
John Recka00cbbd2010-12-16 12:38:19 -08001953 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07001954 }
John Recka00cbbd2010-12-16 12:38:19 -08001955 }.execute();
1956 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001957 }
1958
1959 private class Copy implements OnMenuItemClickListener {
1960 private CharSequence mText;
1961
1962 public boolean onMenuItemClick(MenuItem item) {
1963 copy(mText);
1964 return true;
1965 }
1966
1967 public Copy(CharSequence toCopy) {
1968 mText = toCopy;
1969 }
1970 }
1971
Leon Scroggins63c02662010-11-18 15:16:27 -05001972 private static class Download implements OnMenuItemClickListener {
1973 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001974 private String mText;
1975
1976 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001977 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1978 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001979 return true;
1980 }
1981
Leon Scroggins63c02662010-11-18 15:16:27 -05001982 public Download(Activity activity, String toDownload) {
1983 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001984 mText = toDownload;
1985 }
1986 }
1987
Cary Clark8974d282010-11-22 10:46:05 -05001988 private static class SelectText implements OnMenuItemClickListener {
1989 private WebView mWebView;
1990
1991 public boolean onMenuItemClick(MenuItem item) {
1992 if (mWebView != null) {
1993 return mWebView.selectText();
1994 }
1995 return false;
1996 }
1997
1998 public SelectText(WebView webView) {
1999 mWebView = webView;
2000 }
2001
2002 }
2003
Michael Kolb8233fac2010-10-26 16:08:53 -07002004 /********************** TODO: UI stuff *****************************/
2005
2006 // these methods have been copied, they still need to be cleaned up
2007
2008 /****************** tabs ***************************************************/
2009
2010 // basic tab interactions:
2011
2012 // it is assumed that tabcontrol already knows about the tab
2013 protected void addTab(Tab tab) {
2014 mUi.addTab(tab);
2015 }
2016
2017 protected void removeTab(Tab tab) {
2018 mUi.removeTab(tab);
2019 mTabControl.removeTab(tab);
2020 }
2021
2022 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002023 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08002024 // the tab is guaranteed to have a webview after setCurrentTab
2025 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002026 }
2027
2028 protected void closeEmptyChildTab() {
2029 Tab current = mTabControl.getCurrentTab();
2030 if (current != null
2031 && current.getWebView().copyBackForwardList().getSize() == 0) {
2032 Tab parent = current.getParentTab();
2033 if (parent != null) {
2034 switchToTab(mTabControl.getTabIndex(parent));
2035 closeTab(current);
2036 }
2037 }
2038 }
2039
2040 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002041 // Dismiss the subwindow if applicable.
2042 dismissSubWindow(appTab);
2043 // Since we might kill the WebView, remove it from the
2044 // content view first.
2045 mUi.detachTab(appTab);
2046 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002047 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002048 // TODO: analyze why the remove and add are necessary
2049 mUi.attachTab(appTab);
2050 if (mTabControl.getCurrentTab() != appTab) {
2051 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002052 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002053 } else {
2054 // If the tab was the current tab, we have to attach
2055 // it to the view system again.
2056 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002057 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002058 }
2059 }
2060
2061 // Remove the sub window if it exists. Also called by TabControl when the
2062 // user clicks the 'X' to dismiss a sub window.
2063 public void dismissSubWindow(Tab tab) {
2064 removeSubWindow(tab);
2065 // dismiss the subwindow. This will destroy the WebView.
2066 tab.dismissSubWindow();
2067 getCurrentTopWebView().requestFocus();
2068 }
2069
2070 @Override
2071 public void removeSubWindow(Tab t) {
2072 if (t.getSubWebView() != null) {
2073 mUi.removeSubWindow(t.getSubViewContainer());
2074 }
2075 }
2076
2077 @Override
2078 public void attachSubWindow(Tab tab) {
2079 if (tab.getSubWebView() != null) {
2080 mUi.attachSubWindow(tab.getSubViewContainer());
2081 getCurrentTopWebView().requestFocus();
2082 }
2083 }
2084
Michael Kolb843510f2010-12-09 10:51:49 -08002085 @Override
2086 public Tab openTabToHomePage() {
2087 // check for max tabs
2088 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002089 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2090 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002091 } else {
2092 mUi.showMaxTabsWarning();
2093 return null;
2094 }
2095 }
2096
Michael Kolb18eb3772010-12-10 14:29:51 -08002097 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2098 if (mSettings.openInBackground() && !forceForeground) {
2099 Tab tab = mTabControl.createNewTab(false, null, null,
2100 (parent != null) && parent.isPrivateBrowsingEnabled());
2101 if (tab != null) {
2102 addTab(tab);
2103 WebView view = tab.getWebView();
2104 loadUrl(view, url);
2105 }
2106 return tab;
2107 } else {
2108 return openTabAndShow(parent, new UrlData(url), false, null);
2109 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002110 }
2111
Michael Kolb18eb3772010-12-10 14:29:51 -08002112
Michael Kolb8233fac2010-10-26 16:08:53 -07002113 // This method does a ton of stuff. It will attempt to create a new tab
2114 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2115 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002116 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2117 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002118 final Tab currentTab = mTabControl.getCurrentTab();
2119 if (mTabControl.canCreateNewTab()) {
2120 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002121 urlData.mUrl,
2122 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002123 WebView webview = tab.getWebView();
2124 // We must set the new tab as the current tab to reflect the old
2125 // animation behavior.
2126 addTab(tab);
2127 setActiveTab(tab);
Patrick Scottcd135082011-01-31 18:21:58 -05002128
2129 // Callback to load the url data.
2130 final Runnable load = new Runnable() {
2131 @Override public void run() {
2132 if (!urlData.isEmpty()) {
2133 loadUrlDataIn(tab, urlData);
2134 }
2135 }
2136 };
2137
2138 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings, load);
Michael Kolb8233fac2010-10-26 16:08:53 -07002139 return tab;
2140 } else {
2141 // Get rid of the subwindow if it exists
2142 dismissSubWindow(currentTab);
2143 if (!urlData.isEmpty()) {
2144 // Load the given url.
2145 loadUrlDataIn(currentTab, urlData);
2146 }
2147 return currentTab;
2148 }
2149 }
2150
Michael Kolb8233fac2010-10-26 16:08:53 -07002151 @Override
2152 public Tab openIncognitoTab() {
2153 if (mTabControl.canCreateNewTab()) {
2154 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002155 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002156 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002157 addTab(tab);
2158 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002159 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002160 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002161 } else {
2162 mUi.showMaxTabsWarning();
2163 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002164 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002165 }
2166
2167 /**
2168 * @param index Index of the tab to change to, as defined by
2169 * mTabControl.getTabIndex(Tab t).
2170 * @return boolean True if we successfully switched to a different tab. If
2171 * the indexth tab is null, or if that tab is the same as
2172 * the current one, return false.
2173 */
2174 @Override
2175 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002176 // hide combo view if open
2177 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002178 Tab tab = mTabControl.getTab(index);
2179 Tab currentTab = mTabControl.getCurrentTab();
2180 if (tab == null || tab == currentTab) {
2181 return false;
2182 }
2183 setActiveTab(tab);
2184 return true;
2185 }
2186
2187 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002188 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002189 // hide combo view if open
2190 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002191 final Tab current = mTabControl.getCurrentTab();
2192 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002193 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002194 return;
2195 }
2196 final Tab parent = current.getParentTab();
2197 int indexToShow = -1;
2198 if (parent != null) {
2199 indexToShow = mTabControl.getTabIndex(parent);
2200 } else {
2201 final int currentIndex = mTabControl.getCurrentIndex();
2202 // Try to move to the tab to the right
2203 indexToShow = currentIndex + 1;
2204 if (indexToShow > mTabControl.getTabCount() - 1) {
2205 // Try to move to the tab to the left
2206 indexToShow = currentIndex - 1;
2207 }
2208 }
2209 if (switchToTab(indexToShow)) {
2210 // Close window
2211 closeTab(current);
2212 }
2213 }
2214
2215 /**
2216 * Close the tab, remove its associated title bar, and adjust mTabControl's
2217 * current tab to a valid value.
2218 */
2219 @Override
2220 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002221 // hide combo view if open
2222 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002223 int currentIndex = mTabControl.getCurrentIndex();
2224 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002225 Tab newtab = mTabControl.getTab(currentIndex);
2226 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002227 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002228 }
2229
2230 /**************** TODO: Url loading clean up *******************************/
2231
2232 // Called when loading from context menu or LOAD_URL message
2233 protected void loadUrlFromContext(WebView view, String url) {
2234 // In case the user enters nothing.
2235 if (url != null && url.length() != 0 && view != null) {
2236 url = UrlUtils.smartUrlFilter(url);
2237 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2238 loadUrl(view, url);
2239 }
2240 }
2241 }
2242
2243 /**
2244 * Load the URL into the given WebView and update the title bar
2245 * to reflect the new load. Call this instead of WebView.loadUrl
2246 * directly.
2247 * @param view The WebView used to load url.
2248 * @param url The URL to load.
2249 */
2250 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002251 view.loadUrl(url);
2252 }
2253
2254 /**
2255 * Load UrlData into a Tab and update the title bar to reflect the new
2256 * load. Call this instead of UrlData.loadIn directly.
2257 * @param t The Tab used to load.
2258 * @param data The UrlData being loaded.
2259 */
2260 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002261 data.loadIn(t);
2262 }
2263
John Reck30c714c2010-12-16 17:30:34 -08002264 @Override
2265 public void onUserCanceledSsl(Tab tab) {
2266 WebView web = tab.getWebView();
2267 // TODO: Figure out the "right" behavior
2268 if (web.canGoBack()) {
2269 web.goBack();
2270 } else {
2271 web.loadUrl(mSettings.getHomePage());
2272 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002273 }
2274
2275 void goBackOnePageOrQuit() {
2276 Tab current = mTabControl.getCurrentTab();
2277 if (current == null) {
2278 /*
2279 * Instead of finishing the activity, simply push this to the back
2280 * of the stack and let ActivityManager to choose the foreground
2281 * activity. As BrowserActivity is singleTask, it will be always the
2282 * root of the task. So we can use either true or false for
2283 * moveTaskToBack().
2284 */
2285 mActivity.moveTaskToBack(true);
2286 return;
2287 }
2288 WebView w = current.getWebView();
2289 if (w.canGoBack()) {
2290 w.goBack();
2291 } else {
2292 // Check to see if we are closing a window that was created by
2293 // another window. If so, we switch back to that window.
2294 Tab parent = current.getParentTab();
2295 if (parent != null) {
2296 switchToTab(mTabControl.getTabIndex(parent));
2297 // Now we close the other tab
2298 closeTab(current);
2299 } else {
2300 if (current.closeOnExit()) {
2301 // force the tab's inLoad() to be false as we are going to
2302 // either finish the activity or remove the tab. This will
2303 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002304 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002305 if (mTabControl.getTabCount() == 1) {
2306 mActivity.finish();
2307 return;
2308 }
2309 if (mActivityPaused) {
2310 Log.e(LOGTAG, "BrowserActivity is already paused "
2311 + "while handing goBackOnePageOrQuit.");
2312 }
Michael Kolb70976932010-11-30 11:34:01 -08002313 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002314 removeTab(current);
2315 }
2316 /*
2317 * Instead of finishing the activity, simply push this to the back
2318 * of the stack and let ActivityManager to choose the foreground
2319 * activity. As BrowserActivity is singleTask, it will be always the
2320 * root of the task. So we can use either true or false for
2321 * moveTaskToBack().
2322 */
2323 mActivity.moveTaskToBack(true);
2324 }
2325 }
2326 }
2327
2328 /**
2329 * Feed the previously stored results strings to the BrowserProvider so that
2330 * the SearchDialog will show them instead of the standard searches.
2331 * @param result String to show on the editable line of the SearchDialog.
2332 */
2333 @Override
2334 public void showVoiceSearchResults(String result) {
2335 ContentProviderClient client = mActivity.getContentResolver()
2336 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2337 ContentProvider prov = client.getLocalContentProvider();
2338 BrowserProvider bp = (BrowserProvider) prov;
2339 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2340 client.release();
2341
2342 Bundle bundle = createGoogleSearchSourceBundle(
2343 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2344 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2345 startSearch(result, false, bundle, false);
2346 }
2347
2348 private void startSearch(String initialQuery, boolean selectInitialQuery,
2349 Bundle appSearchData, boolean globalSearch) {
2350 if (appSearchData == null) {
2351 appSearchData = createGoogleSearchSourceBundle(
2352 GOOGLE_SEARCH_SOURCE_TYPE);
2353 }
2354
2355 SearchEngine searchEngine = mSettings.getSearchEngine();
2356 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2357 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2358 }
2359 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2360 globalSearch);
2361 }
2362
2363 private Bundle createGoogleSearchSourceBundle(String source) {
2364 Bundle bundle = new Bundle();
2365 bundle.putString(Search.SOURCE, source);
2366 return bundle;
2367 }
2368
2369 /**
2370 * handle key events in browser
2371 *
2372 * @param keyCode
2373 * @param event
2374 * @return true if handled, false to pass to super
2375 */
2376 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002377 boolean noModifiers = event.hasNoModifiers();
2378
Michael Kolb8233fac2010-10-26 16:08:53 -07002379 // Even if MENU is already held down, we need to call to super to open
2380 // the IME on long press.
Cary Clark160bbb92011-01-10 11:17:07 -05002381 if (!noModifiers && KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002382 mMenuIsDown = true;
2383 return false;
2384 }
2385 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2386 // still down, we don't want to trigger the search. Pretend to consume
2387 // the key and do nothing.
2388 if (mMenuIsDown) return true;
2389
Cary Clark8ff8c662010-12-29 15:03:05 -05002390 WebView webView = getCurrentTopWebView();
2391 if (webView == null) return false;
2392
Cary Clark160bbb92011-01-10 11:17:07 -05002393 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2394 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002395
Michael Kolb8233fac2010-10-26 16:08:53 -07002396 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002397 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002398 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002399 stopLoading();
2400 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002401 case KeyEvent.KEYCODE_SPACE:
2402 // WebView/WebTextView handle the keys in the KeyDown. As
2403 // the Activity's shortcut keys are only handled when WebView
2404 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002405 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002406 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002407 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002408 pageDown();
2409 }
2410 return true;
2411 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002412 if (!noModifiers) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002413 if (event.getRepeatCount() == 0) {
2414 event.startTracking();
2415 return true;
2416 } else if (mUi.showsWeb()
2417 && event.isLongPress()) {
2418 bookmarksOrHistoryPicker(true);
2419 return true;
2420 }
2421 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002422 case KeyEvent.KEYCODE_DPAD_LEFT:
2423 if (ctrl) {
2424 webView.goBack();
2425 return true;
2426 }
2427 break;
2428 case KeyEvent.KEYCODE_DPAD_RIGHT:
2429 if (ctrl) {
2430 webView.goForward();
2431 return true;
2432 }
2433 break;
2434 case KeyEvent.KEYCODE_A:
2435 if (ctrl) {
2436 webView.selectAll();
2437 return true;
2438 }
2439 break;
Michael Kolba4183062011-01-16 10:43:21 -08002440// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002441 case KeyEvent.KEYCODE_C:
2442 if (ctrl) {
2443 webView.copySelection();
2444 return true;
2445 }
2446 break;
Michael Kolba4183062011-01-16 10:43:21 -08002447// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002448// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002449// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002450// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002451// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002452// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002453// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002454// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002455// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002456// case KeyEvent.KEYCODE_M: // unused
2457// case KeyEvent.KEYCODE_N: // in Chrome: new window
2458// case KeyEvent.KEYCODE_O: // in Chrome: open file
2459// case KeyEvent.KEYCODE_P: // in Chrome: print page
2460// case KeyEvent.KEYCODE_Q: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002461// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002462// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2463 case KeyEvent.KEYCODE_T:
2464 if (ctrl) {
2465 if (event.isShiftPressed()) {
2466 openIncognitoTab();
2467 } else {
2468 openTabToHomePage();
2469 }
2470 return true;
2471 }
2472 break;
2473// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2474// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolba4183062011-01-16 10:43:21 -08002475// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002476// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2477// case KeyEvent.KEYCODE_Y: // unused
2478// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002479 }
Michael Kolba4183062011-01-16 10:43:21 -08002480 // if we get here, it is a regular key and webview is not null
2481 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002482 }
2483
2484 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002485 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002486 switch(keyCode) {
2487 case KeyEvent.KEYCODE_MENU:
2488 mMenuIsDown = false;
2489 break;
2490 case KeyEvent.KEYCODE_BACK:
2491 if (event.isTracking() && !event.isCanceled()) {
2492 onBackKey();
2493 return true;
2494 }
2495 break;
2496 }
2497 return false;
2498 }
2499
2500 public boolean isMenuDown() {
2501 return mMenuIsDown;
2502 }
2503
Ben Murdoch8029a772010-11-16 11:58:21 +00002504 public void setupAutoFill(Message message) {
2505 // Open the settings activity at the AutoFill profile fragment so that
2506 // the user can create a new profile. When they return, we will dispatch
2507 // the message so that we can autofill the form using their new profile.
2508 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2509 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2510 AutoFillSettingsFragment.class.getName());
2511 mAutoFillSetupMessage = message;
2512 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2513 }
John Reckb3417f02011-01-14 11:01:05 -08002514
2515 @Override
2516 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2517 mOptionsMenuHandler = handler;
2518 }
2519
2520 @Override
2521 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2522 if (mOptionsMenuHandler == handler) {
2523 mOptionsMenuHandler = null;
2524 }
2525 }
2526
Michael Kolb8233fac2010-10-26 16:08:53 -07002527}