blob: acd76ddf7f25d1e72e7491f75e83cf6f87fefd82 [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;
36import android.database.Cursor;
37import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteException;
39import 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;
53import android.provider.BrowserContract.History;
54import android.provider.BrowserContract.Images;
55import android.provider.ContactsContract;
56import android.provider.ContactsContract.Intents.Insert;
57import android.speech.RecognizerResultsIntent;
58import android.text.TextUtils;
59import android.util.Log;
60import android.view.ActionMode;
61import android.view.ContextMenu;
62import android.view.ContextMenu.ContextMenuInfo;
63import android.view.Gravity;
64import android.view.KeyEvent;
65import android.view.LayoutInflater;
66import 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;
80import android.widget.TextView;
81
82import java.io.ByteArrayOutputStream;
83import java.io.File;
84import java.net.URLEncoder;
85import java.util.Calendar;
86import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080087import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070088
89/**
90 * Controller for browser
91 */
92public class Controller
93 implements WebViewController, UiController {
94
95 private static final String LOGTAG = "Controller";
96
97 // public message ids
98 public final static int LOAD_URL = 1001;
99 public final static int STOP_LOAD = 1002;
100
101 // Message Ids
102 private static final int FOCUS_NODE_HREF = 102;
103 private static final int RELEASE_WAKELOCK = 107;
104
105 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
106
107 private static final int OPEN_BOOKMARKS = 201;
108
109 private static final int EMPTY_MENU = -1;
110
111 // Keep this initial progress in sync with initialProgressValue (* 100)
112 // in ProgressTracker.cpp
113 private final static int INITIAL_PROGRESS = 10;
114
115 // activity requestCode
116 final static int PREFERENCES_PAGE = 3;
117 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000118 final static int AUTOFILL_SETUP = 5;
119
Michael Kolb8233fac2010-10-26 16:08:53 -0700120 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
121
122 // As the ids are dynamically created, we can't guarantee that they will
123 // be in sequence, so this static array maps ids to a window number.
124 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
125 { R.id.window_one_menu_id, R.id.window_two_menu_id,
126 R.id.window_three_menu_id, R.id.window_four_menu_id,
127 R.id.window_five_menu_id, R.id.window_six_menu_id,
128 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
129
130 // "source" parameter for Google search through search key
131 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
132 // "source" parameter for Google search through simplily type
133 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
134
135 private Activity mActivity;
136 private UI mUi;
137 private TabControl mTabControl;
138 private BrowserSettings mSettings;
139 private WebViewFactory mFactory;
140
141 private WakeLock mWakeLock;
142
143 private UrlHandler mUrlHandler;
144 private UploadHandler mUploadHandler;
145 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700146 private PageDialogsHandler mPageDialogsHandler;
147 private NetworkStateHandler mNetworkHandler;
148
Ben Murdoch8029a772010-11-16 11:58:21 +0000149 private Message mAutoFillSetupMessage;
150
Michael Kolb8233fac2010-10-26 16:08:53 -0700151 private boolean mShouldShowErrorConsole;
152
153 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
154
155 // FIXME, temp address onPrepareMenu performance problem.
156 // When we move everything out of view, we should rewrite this.
157 private int mCurrentMenuState = 0;
158 private int mMenuState = R.id.MAIN_MENU;
159 private int mOldMenuState = EMPTY_MENU;
160 private Menu mCachedMenu;
161
162 // Used to prevent chording to result in firing two shortcuts immediately
163 // one after another. Fixes bug 1211714.
164 boolean mCanChord;
165 private boolean mMenuIsDown;
166
167 // For select and find, we keep track of the ActionMode so that
168 // finish() can be called as desired.
169 private ActionMode mActionMode;
170
171 /**
172 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
173 * of whether the configuration has changed. The first onMenuOpened call
174 * after a configuration change is simply a reopening of the same menu
175 * (i.e. mIconView did not change).
176 */
177 private boolean mConfigChanged;
178
179 /**
180 * Keeps track of whether the options menu is open. This is important in
181 * determining whether to show or hide the title bar overlay
182 */
183 private boolean mOptionsMenuOpen;
184
185 /**
186 * Whether or not the options menu is in its bigger, popup menu form. When
187 * true, we want the title bar overlay to be gone. When false, we do not.
188 * Only meaningful if mOptionsMenuOpen is true.
189 */
190 private boolean mExtendedMenuOpen;
191
192 private boolean mInLoad;
193
194 private boolean mActivityPaused = true;
195 private boolean mLoadStopped;
196
197 private Handler mHandler;
198
199 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
200 @Override
201 public Void doInBackground(File... files) {
202 if (files != null) {
203 for (File f : files) {
204 if (!f.delete()) {
205 Log.e(LOGTAG, f.getPath() + " was not deleted");
206 }
207 }
208 }
209 return null;
210 }
211 }
212
213 public Controller(Activity browser) {
214 mActivity = browser;
215 mSettings = BrowserSettings.getInstance();
216 mTabControl = new TabControl(this);
217 mSettings.setController(this);
218
219 mUrlHandler = new UrlHandler(this);
220 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700221 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
222
223 PowerManager pm = (PowerManager) mActivity
224 .getSystemService(Context.POWER_SERVICE);
225 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
226
227 startHandler();
228
229 mNetworkHandler = new NetworkStateHandler(mActivity, this);
230 // Start watching the default geolocation permissions
231 mSystemAllowGeolocationOrigins =
232 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
233 mSystemAllowGeolocationOrigins.start();
234
235 retainIconsOnStartup();
236 }
237
238 void start(Bundle icicle, Intent intent) {
239 // Unless the last browser usage was within 24 hours, destroy any
240 // remaining incognito tabs.
241
242 Calendar lastActiveDate = icicle != null ?
243 (Calendar) icicle.getSerializable("lastActiveDate") : null;
244 Calendar today = Calendar.getInstance();
245 Calendar yesterday = Calendar.getInstance();
246 yesterday.add(Calendar.DATE, -1);
247
Michael Kolb1bf23132010-11-19 12:55:12 -0800248 boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700249 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800250 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700251
Michael Kolb1bf23132010-11-19 12:55:12 -0800252 if (!mTabControl.restoreState(icicle, restoreIncognitoTabs,
253 mUi.needsRestoreAllTabs())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700254 // there is no quit on Android. But if we can't restore the state,
255 // we can treat it as a new Browser, remove the old session cookies.
256 CookieManager.getInstance().removeSessionCookie();
257 // remove any incognito files
Steve Block83101a82010-11-26 11:33:35 +0000258 WebView.cleanupPrivateBrowsingFiles();
Michael Kolb8233fac2010-10-26 16:08:53 -0700259 final Bundle extra = intent.getExtras();
260 // Create an initial tab.
261 // If the intent is ACTION_VIEW and data is not null, the Browser is
262 // invoked to view the content by another application. In this case,
263 // the tab will be close when exit.
264 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
265
266 String action = intent.getAction();
267 final Tab t = mTabControl.createNewTab(
268 (Intent.ACTION_VIEW.equals(action) &&
269 intent.getData() != null)
270 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
271 .equals(action),
272 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
273 urlData.mUrl, false);
274 addTab(t);
275 setActiveTab(t);
276 WebView webView = t.getWebView();
277 if (extra != null) {
278 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
279 if (scale > 0 && scale <= 1000) {
280 webView.setInitialScale(scale);
281 }
282 }
283
284 if (urlData.isEmpty()) {
285 loadUrl(webView, mSettings.getHomePage());
286 } else {
287 loadUrlDataIn(t, urlData);
288 }
289 } else {
Michael Kolb1bf23132010-11-19 12:55:12 -0800290 mUi.updateTabs(mTabControl.getTabs());
291 if (!restoreIncognitoTabs) {
Steve Block83101a82010-11-26 11:33:35 +0000292 WebView.cleanupPrivateBrowsingFiles();
Michael Kolb8233fac2010-10-26 16:08:53 -0700293 }
294 // TabControl.restoreState() will create a new tab even if
295 // restoring the state fails.
296 setActiveTab(mTabControl.getCurrentTab());
297 }
298 // clear up the thumbnail directory, which is no longer used;
299 // ideally this should only be run once after an upgrade from
300 // a previous version of the browser
301 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
302 .listFiles());
303 // Read JavaScript flags if it exists.
304 String jsFlags = getSettings().getJsFlags();
305 if (jsFlags.trim().length() != 0) {
306 getCurrentWebView().setJsFlags(jsFlags);
307 }
308 }
309
310 void setWebViewFactory(WebViewFactory factory) {
311 mFactory = factory;
312 }
313
Michael Kolb1514bb72010-11-22 09:11:48 -0800314 @Override
315 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700316 return mFactory;
317 }
318
319 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800320 public void createSubWindow(Tab tab) {
321 endActionMode();
322 WebView mainView = tab.getWebView();
323 WebView subView = mFactory.createWebView((mainView == null)
324 ? false
325 : mainView.isPrivateBrowsingEnabled());
326 mUi.createSubWindow(tab, subView);
327 }
328
329 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700330 public Activity getActivity() {
331 return mActivity;
332 }
333
334 void setUi(UI ui) {
335 mUi = ui;
336 }
337
338 BrowserSettings getSettings() {
339 return mSettings;
340 }
341
342 IntentHandler getIntentHandler() {
343 return mIntentHandler;
344 }
345
346 @Override
347 public UI getUi() {
348 return mUi;
349 }
350
351 int getMaxTabs() {
352 return mActivity.getResources().getInteger(R.integer.max_tabs);
353 }
354
355 @Override
356 public TabControl getTabControl() {
357 return mTabControl;
358 }
359
Michael Kolb1bf23132010-11-19 12:55:12 -0800360 @Override
361 public List<Tab> getTabs() {
362 return mTabControl.getTabs();
363 }
364
Michael Kolb8233fac2010-10-26 16:08:53 -0700365 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000366 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700367 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000368 // WebIconDatabase needs to be retrieved on the UI thread so that if
369 // it has not been created successfully yet the Handler is started on the
370 // UI thread.
371 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
372 }
373
374 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
375 private WebIconDatabase mDb;
376
377 public RetainIconsOnStartupTask(WebIconDatabase db) {
378 mDb = db;
379 }
380
381 protected Void doInBackground(Void... unused) {
382 mDb.open(mActivity.getDir("icons", 0).getPath());
383 Cursor c = null;
384 try {
385 c = Browser.getAllBookmarks(mActivity.getContentResolver());
386 if (c.moveToFirst()) {
387 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
388 do {
389 String url = c.getString(urlIndex);
390 mDb.retainIconForPageUrl(url);
391 } while (c.moveToNext());
392 }
393 } catch (IllegalStateException e) {
394 Log.e(LOGTAG, "retainIconsOnStartup", e);
395 } finally {
396 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700397 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000398
399 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700400 }
401 }
402
403 private void startHandler() {
404 mHandler = new Handler() {
405
406 @Override
407 public void handleMessage(Message msg) {
408 switch (msg.what) {
409 case OPEN_BOOKMARKS:
410 bookmarksOrHistoryPicker(false);
411 break;
412 case FOCUS_NODE_HREF:
413 {
414 String url = (String) msg.getData().get("url");
415 String title = (String) msg.getData().get("title");
416 if (TextUtils.isEmpty(url)) {
417 break;
418 }
419 HashMap focusNodeMap = (HashMap) msg.obj;
420 WebView view = (WebView) focusNodeMap.get("webview");
421 // Only apply the action if the top window did not change.
422 if (getCurrentTopWebView() != view) {
423 break;
424 }
425 switch (msg.arg1) {
426 case R.id.open_context_menu_id:
427 case R.id.view_image_context_menu_id:
428 loadUrlFromContext(getCurrentTopWebView(), url);
429 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500430 case R.id.open_newtab_context_menu_id:
431 final Tab parent = mTabControl.getCurrentTab();
432 final Tab newTab = openTab(url, false);
433 if (newTab != null && newTab != parent) {
434 parent.addChildTab(newTab);
435 }
436 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700437 case R.id.bookmark_context_menu_id:
438 Intent intent = new Intent(mActivity,
439 AddBookmarkPage.class);
440 intent.putExtra(BrowserContract.Bookmarks.URL, url);
441 intent.putExtra(BrowserContract.Bookmarks.TITLE,
442 title);
443 mActivity.startActivity(intent);
444 break;
445 case R.id.share_link_context_menu_id:
446 sharePage(mActivity, title, url, null,
447 null);
448 break;
449 case R.id.copy_link_context_menu_id:
450 copy(url);
451 break;
452 case R.id.save_link_context_menu_id:
453 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500454 DownloadHandler.onDownloadStartNoStream(
455 mActivity, url, null, null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -0700456 break;
457 }
458 break;
459 }
460
461 case LOAD_URL:
462 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
463 break;
464
465 case STOP_LOAD:
466 stopLoading();
467 break;
468
469 case RELEASE_WAKELOCK:
470 if (mWakeLock.isHeld()) {
471 mWakeLock.release();
472 // if we reach here, Browser should be still in the
473 // background loading after WAKELOCK_TIMEOUT (5-min).
474 // To avoid burning the battery, stop loading.
475 mTabControl.stopAllLoading();
476 }
477 break;
478
479 case UPDATE_BOOKMARK_THUMBNAIL:
480 WebView view = (WebView) msg.obj;
481 if (view != null) {
482 updateScreenshot(view);
483 }
484 break;
485 }
486 }
487 };
488
489 }
490
491 /**
492 * Share a page, providing the title, url, favicon, and a screenshot. Uses
493 * an {@link Intent} to launch the Activity chooser.
494 * @param c Context used to launch a new Activity.
495 * @param title Title of the page. Stored in the Intent with
496 * {@link Intent#EXTRA_SUBJECT}
497 * @param url URL of the page. Stored in the Intent with
498 * {@link Intent#EXTRA_TEXT}
499 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
500 * with {@link Browser#EXTRA_SHARE_FAVICON}
501 * @param screenshot Bitmap of a screenshot of the page. Stored in the
502 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
503 */
504 static final void sharePage(Context c, String title, String url,
505 Bitmap favicon, Bitmap screenshot) {
506 Intent send = new Intent(Intent.ACTION_SEND);
507 send.setType("text/plain");
508 send.putExtra(Intent.EXTRA_TEXT, url);
509 send.putExtra(Intent.EXTRA_SUBJECT, title);
510 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
511 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
512 try {
513 c.startActivity(Intent.createChooser(send, c.getString(
514 R.string.choosertitle_sharevia)));
515 } catch(android.content.ActivityNotFoundException ex) {
516 // if no app handles it, do nothing
517 }
518 }
519
520 private void copy(CharSequence text) {
521 ClipboardManager cm = (ClipboardManager) mActivity
522 .getSystemService(Context.CLIPBOARD_SERVICE);
523 cm.setText(text);
524 }
525
526 // lifecycle
527
528 protected void onConfgurationChanged(Configuration config) {
529 mConfigChanged = true;
530 if (mPageDialogsHandler != null) {
531 mPageDialogsHandler.onConfigurationChanged(config);
532 }
533 mUi.onConfigurationChanged(config);
534 }
535
536 @Override
537 public void handleNewIntent(Intent intent) {
538 mIntentHandler.onNewIntent(intent);
539 }
540
541 protected void onPause() {
542 if (mActivityPaused) {
543 Log.e(LOGTAG, "BrowserActivity is already paused.");
544 return;
545 }
546 mTabControl.pauseCurrentTab();
547 mActivityPaused = true;
548 if (mTabControl.getCurrentIndex() >= 0 &&
549 !pauseWebViewTimers(mActivityPaused)) {
550 mWakeLock.acquire();
551 mHandler.sendMessageDelayed(mHandler
552 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
553 }
554 mUi.onPause();
555 mNetworkHandler.onPause();
556
557 WebView.disablePlatformNotifications();
558 }
559
560 void onSaveInstanceState(Bundle outState) {
561 // the default implementation requires each view to have an id. As the
562 // browser handles the state itself and it doesn't use id for the views,
563 // don't call the default implementation. Otherwise it will trigger the
564 // warning like this, "couldn't save which view has focus because the
565 // focused view XXX has no id".
566
567 // Save all the tabs
568 mTabControl.saveState(outState);
569 // Save time so that we know how old incognito tabs (if any) are.
570 outState.putSerializable("lastActiveDate", Calendar.getInstance());
571 }
572
573 void onResume() {
574 if (!mActivityPaused) {
575 Log.e(LOGTAG, "BrowserActivity is already resumed.");
576 return;
577 }
578 mTabControl.resumeCurrentTab();
579 mActivityPaused = false;
580 resumeWebViewTimers();
581
582 if (mWakeLock.isHeld()) {
583 mHandler.removeMessages(RELEASE_WAKELOCK);
584 mWakeLock.release();
585 }
586 mUi.onResume();
587 mNetworkHandler.onResume();
588 WebView.enablePlatformNotifications();
589 }
590
591 private void resumeWebViewTimers() {
592 Tab tab = mTabControl.getCurrentTab();
593 if (tab == null) return; // monkey can trigger this
594 boolean inLoad = tab.inPageLoad();
595 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
596 CookieSyncManager.getInstance().startSync();
597 WebView w = tab.getWebView();
598 if (w != null) {
599 w.resumeTimers();
600 }
601 }
602 }
603
604 private boolean pauseWebViewTimers(boolean activityPaused) {
605 Tab tab = mTabControl.getCurrentTab();
606 boolean inLoad = tab.inPageLoad();
607 if (activityPaused && !inLoad) {
608 CookieSyncManager.getInstance().stopSync();
609 WebView w = getCurrentWebView();
610 if (w != null) {
611 w.pauseTimers();
612 }
613 return true;
614 } else {
615 return false;
616 }
617 }
618
619 void onDestroy() {
620 if (mUploadHandler != null) {
621 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
622 mUploadHandler = null;
623 }
624 if (mTabControl == null) return;
625 mUi.onDestroy();
626 // Remove the current tab and sub window
627 Tab t = mTabControl.getCurrentTab();
628 if (t != null) {
629 dismissSubWindow(t);
630 removeTab(t);
631 }
632 // Destroy all the tabs
633 mTabControl.destroy();
634 WebIconDatabase.getInstance().close();
635 // Stop watching the default geolocation permissions
636 mSystemAllowGeolocationOrigins.stop();
637 mSystemAllowGeolocationOrigins = null;
638 }
639
640 protected boolean isActivityPaused() {
641 return mActivityPaused;
642 }
643
644 protected void onLowMemory() {
645 mTabControl.freeMemory();
646 }
647
648 @Override
649 public boolean shouldShowErrorConsole() {
650 return mShouldShowErrorConsole;
651 }
652
653 protected void setShouldShowErrorConsole(boolean show) {
654 if (show == mShouldShowErrorConsole) {
655 // Nothing to do.
656 return;
657 }
658 mShouldShowErrorConsole = show;
659 Tab t = mTabControl.getCurrentTab();
660 if (t == null) {
661 // There is no current tab so we cannot toggle the error console
662 return;
663 }
664 mUi.setShouldShowErrorConsole(t, show);
665 }
666
667 @Override
668 public void stopLoading() {
669 mLoadStopped = true;
670 Tab tab = mTabControl.getCurrentTab();
671 resetTitleAndRevertLockIcon(tab);
672 WebView w = getCurrentTopWebView();
673 w.stopLoading();
674 // FIXME: before refactor, it is using mWebViewClient. So I keep the
675 // same logic here. But for subwindow case, should we call into the main
676 // WebView's onPageFinished as we never call its onPageStarted and if
677 // the page finishes itself, we don't call onPageFinished.
678 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
679 w.getUrl());
680 mUi.onPageStopped(tab);
681 }
682
683 boolean didUserStopLoading() {
684 return mLoadStopped;
685 }
686
687 // WebViewController
688
689 @Override
690 public void onPageStarted(Tab tab, WebView view, String url, Bitmap favicon) {
691
692 // We've started to load a new page. If there was a pending message
693 // to save a screenshot then we will now take the new page and save
694 // an incorrect screenshot. Therefore, remove any pending thumbnail
695 // messages from the queue.
696 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
697 view);
698
699 // reset sync timer to avoid sync starts during loading a page
700 CookieSyncManager.getInstance().resetSync();
701
702 if (!mNetworkHandler.isNetworkUp()) {
703 view.setNetworkAvailable(false);
704 }
705
706 // when BrowserActivity just starts, onPageStarted may be called before
707 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
708 // to start the timer. As we won't switch tabs while an activity is in
709 // pause state, we can ensure calling resume and pause in pair.
710 if (mActivityPaused) {
711 resumeWebViewTimers();
712 }
713 mLoadStopped = false;
714 if (!mNetworkHandler.isNetworkUp()) {
715 mNetworkHandler.createAndShowNetworkDialog();
716 }
717 endActionMode();
718
719 mUi.onPageStarted(tab, url, favicon);
720
721 // Show some progress so that the user knows the page is beginning to
722 // load
723 onProgressChanged(tab, INITIAL_PROGRESS);
724
725 // update the bookmark database for favicon
726 maybeUpdateFavicon(tab, null, url, favicon);
727
728 Performance.tracePageStart(url);
729
730 // Performance probe
731 if (false) {
732 Performance.onPageStarted();
733 }
734
735 }
736
737 @Override
738 public void onPageFinished(Tab tab, String url) {
739 mUi.onPageFinished(tab, url);
740 if (!tab.isPrivateBrowsingEnabled()) {
741 if (tab.inForeground() && !didUserStopLoading()
742 || !tab.inForeground()) {
743 // Only update the bookmark screenshot if the user did not
744 // cancel the load early.
745 mHandler.sendMessageDelayed(mHandler.obtainMessage(
746 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab.getWebView()),
747 500);
748 }
749 }
750 // pause the WebView timer and release the wake lock if it is finished
751 // while BrowserActivity is in pause state.
752 if (mActivityPaused && pauseWebViewTimers(mActivityPaused)) {
753 if (mWakeLock.isHeld()) {
754 mHandler.removeMessages(RELEASE_WAKELOCK);
755 mWakeLock.release();
756 }
757 }
758 // Performance probe
759 if (false) {
760 Performance.onPageFinished(url);
761 }
762
763 Performance.tracePageFinished();
764 }
765
766 @Override
767 public void onProgressChanged(Tab tab, int newProgress) {
768
769 if (newProgress == 100) {
770 CookieSyncManager.getInstance().sync();
771 // onProgressChanged() may continue to be called after the main
772 // frame has finished loading, as any remaining sub frames continue
773 // to load. We'll only get called once though with newProgress as
774 // 100 when everything is loaded. (onPageFinished is called once
775 // when the main frame completes loading regardless of the state of
776 // any sub frames so calls to onProgressChanges may continue after
777 // onPageFinished has executed)
778 if (mInLoad) {
779 mInLoad = false;
780 updateInLoadMenuItems(mCachedMenu);
781 }
782 } else {
783 if (!mInLoad) {
784 // onPageFinished may have already been called but a subframe is
785 // still loading and updating the progress. Reset mInLoad and
786 // update the menu items.
787 mInLoad = true;
788 updateInLoadMenuItems(mCachedMenu);
789 }
790 }
791 mUi.onProgressChanged(tab, newProgress);
792 }
793
794 @Override
795 public void onReceivedTitle(Tab tab, final String title) {
796 final String pageUrl = tab.getWebView().getUrl();
797 setUrlTitle(tab, pageUrl, title);
798 if (pageUrl == null || pageUrl.length()
799 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
800 return;
801 }
802 // Update the title in the history database if not in private browsing mode
803 if (!tab.isPrivateBrowsingEnabled()) {
804 new AsyncTask<Void, Void, Void>() {
805 @Override
806 protected Void doInBackground(Void... unused) {
807 // See if we can find the current url in our history
808 // database and add the new title to it.
809 String url = pageUrl;
810 if (url.startsWith("http://www.")) {
811 url = url.substring(11);
812 } else if (url.startsWith("http://")) {
813 url = url.substring(4);
814 }
815 // Escape wildcards for LIKE operator.
816 url = url.replace("\\", "\\\\").replace("%", "\\%")
817 .replace("_", "\\_");
818 Cursor c = null;
819 try {
820 final ContentResolver cr =
821 getActivity().getContentResolver();
822 String selection = History.URL + " LIKE ? ESCAPE '\\'";
823 String [] selectionArgs = new String[] { "%" + url };
824 ContentValues values = new ContentValues();
825 values.put(History.TITLE, title);
826 cr.update(History.CONTENT_URI, values, selection,
827 selectionArgs);
828 } catch (IllegalStateException e) {
829 Log.e(LOGTAG, "Tab onReceived title", e);
830 } catch (SQLiteException ex) {
831 Log.e(LOGTAG,
832 "onReceivedTitle() caught SQLiteException: ",
833 ex);
834 } finally {
835 if (c != null) c.close();
836 }
837 return null;
838 }
839 }.execute();
840 }
841 }
842
843 @Override
844 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
845 mUi.setFavicon(tab, icon);
846 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
847 }
848
849 @Override
850 public boolean shouldOverrideUrlLoading(WebView view, String url) {
851 return mUrlHandler.shouldOverrideUrlLoading(view, url);
852 }
853
854 @Override
855 public boolean shouldOverrideKeyEvent(KeyEvent event) {
856 if (mMenuIsDown) {
857 // only check shortcut key when MENU is held
858 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
859 event);
860 } else {
861 return false;
862 }
863 }
864
865 @Override
866 public void onUnhandledKeyEvent(KeyEvent event) {
867 if (!isActivityPaused()) {
868 if (event.getAction() == KeyEvent.ACTION_DOWN) {
869 mActivity.onKeyDown(event.getKeyCode(), event);
870 } else {
871 mActivity.onKeyUp(event.getKeyCode(), event);
872 }
873 }
874 }
875
876 @Override
877 public void doUpdateVisitedHistory(Tab tab, String url,
878 boolean isReload) {
879 // Don't save anything in private browsing mode
880 if (tab.isPrivateBrowsingEnabled()) return;
881
882 if (url.regionMatches(true, 0, "about:", 0, 6)) {
883 return;
884 }
885 // remove "client" before updating it to the history so that it wont
886 // show up in the auto-complete list.
887 int index = url.indexOf("client=ms-");
888 if (index > 0 && url.contains(".google.")) {
889 int end = url.indexOf('&', index);
890 if (end > 0) {
891 url = url.substring(0, index)
892 .concat(url.substring(end + 1));
893 } else {
894 // the url.charAt(index-1) should be either '?' or '&'
895 url = url.substring(0, index-1);
896 }
897 }
898 final ContentResolver cr = getActivity().getContentResolver();
899 final String newUrl = url;
900 new AsyncTask<Void, Void, Void>() {
901 @Override
902 protected Void doInBackground(Void... unused) {
903 Browser.updateVisitedHistory(cr, newUrl, true);
904 return null;
905 }
906 }.execute();
907 WebIconDatabase.getInstance().retainIconForPageUrl(url);
908 }
909
910 @Override
911 public void getVisitedHistory(final ValueCallback<String[]> callback) {
912 AsyncTask<Void, Void, String[]> task =
913 new AsyncTask<Void, Void, String[]>() {
914 @Override
915 public String[] doInBackground(Void... unused) {
916 return Browser.getVisitedHistory(mActivity.getContentResolver());
917 }
918 @Override
919 public void onPostExecute(String[] result) {
920 callback.onReceiveValue(result);
921 }
922 };
923 task.execute();
924 }
925
926 @Override
927 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
928 final HttpAuthHandler handler, final String host,
929 final String realm) {
930 String username = null;
931 String password = null;
932
933 boolean reuseHttpAuthUsernamePassword
934 = handler.useHttpAuthUsernamePassword();
935
936 if (reuseHttpAuthUsernamePassword && view != null) {
937 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
938 if (credentials != null && credentials.length == 2) {
939 username = credentials[0];
940 password = credentials[1];
941 }
942 }
943
944 if (username != null && password != null) {
945 handler.proceed(username, password);
946 } else {
947 if (tab.inForeground()) {
948 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
949 } else {
950 handler.cancel();
951 }
952 }
953 }
954
955 @Override
956 public void onDownloadStart(Tab tab, String url, String userAgent,
957 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500958 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
959 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700960 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
961 // This Tab was opened for the sole purpose of downloading a
962 // file. Remove it.
963 if (tab == mTabControl.getCurrentTab()) {
964 // In this case, the Tab is still on top.
965 goBackOnePageOrQuit();
966 } else {
967 // In this case, it is not.
968 closeTab(tab);
969 }
970 }
971 }
972
973 @Override
974 public Bitmap getDefaultVideoPoster() {
975 return mUi.getDefaultVideoPoster();
976 }
977
978 @Override
979 public View getVideoLoadingProgressView() {
980 return mUi.getVideoLoadingProgressView();
981 }
982
983 @Override
984 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
985 SslError error) {
986 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
987 }
988
989 // helper method
990
991 /*
992 * Update the favorites icon if the private browsing isn't enabled and the
993 * icon is valid.
994 */
995 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
996 final String url, Bitmap favicon) {
997 if (favicon == null) {
998 return;
999 }
1000 if (!tab.isPrivateBrowsingEnabled()) {
1001 Bookmarks.updateFavicon(mActivity
1002 .getContentResolver(), originalUrl, url, favicon);
1003 }
1004 }
1005
1006 // end WebViewController
1007
1008 protected void pageUp() {
1009 getCurrentTopWebView().pageUp(false);
1010 }
1011
1012 protected void pageDown() {
1013 getCurrentTopWebView().pageDown(false);
1014 }
1015
1016 // callback from phone title bar
1017 public void editUrl() {
1018 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1019 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1020 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1021 null, false);
1022 }
1023
1024 public void activateVoiceSearchMode(String title) {
1025 mUi.showVoiceTitleBar(title);
1026 }
1027
1028 public void revertVoiceSearchMode(Tab tab) {
1029 mUi.revertVoiceTitleBar(tab);
1030 }
1031
1032 public void showCustomView(Tab tab, View view,
1033 WebChromeClient.CustomViewCallback callback) {
1034 if (tab.inForeground()) {
1035 if (mUi.isCustomViewShowing()) {
1036 callback.onCustomViewHidden();
1037 return;
1038 }
1039 mUi.showCustomView(view, callback);
1040 // Save the menu state and set it to empty while the custom
1041 // view is showing.
1042 mOldMenuState = mMenuState;
1043 mMenuState = EMPTY_MENU;
1044 }
1045 }
1046
1047 @Override
1048 public void hideCustomView() {
1049 if (mUi.isCustomViewShowing()) {
1050 mUi.onHideCustomView();
1051 // Reset the old menu state.
1052 mMenuState = mOldMenuState;
1053 mOldMenuState = EMPTY_MENU;
1054 }
1055 }
1056
1057 protected void onActivityResult(int requestCode, int resultCode,
1058 Intent intent) {
1059 if (getCurrentTopWebView() == null) return;
1060 switch (requestCode) {
1061 case PREFERENCES_PAGE:
1062 if (resultCode == Activity.RESULT_OK && intent != null) {
1063 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1064 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1065 mTabControl.removeParentChildRelationShips();
1066 }
1067 }
1068 break;
1069 case FILE_SELECTED:
1070 // Choose a file from the file picker.
1071 if (null == mUploadHandler) break;
1072 mUploadHandler.onResult(resultCode, intent);
1073 mUploadHandler = null;
1074 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001075 case AUTOFILL_SETUP:
1076 // Determine whether a profile was actually set up or not
1077 // and if so, send the message back to the WebTextView to
1078 // fill the form with the new profile.
1079 if (getSettings().getAutoFillProfile() != null) {
1080 mAutoFillSetupMessage.sendToTarget();
1081 mAutoFillSetupMessage = null;
1082 }
1083 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001084 default:
1085 break;
1086 }
1087 getCurrentTopWebView().requestFocus();
1088 }
1089
1090 /**
1091 * Open the Go page.
1092 * @param startWithHistory If true, open starting on the history tab.
1093 * Otherwise, start with the bookmarks tab.
1094 */
1095 @Override
1096 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1097 if (mTabControl.getCurrentWebView() == null) {
1098 return;
1099 }
1100 Bundle extras = new Bundle();
1101 // Disable opening in a new window if we have maxed out the windows
1102 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1103 !mTabControl.canCreateNewTab());
1104 mUi.showComboView(startWithHistory, extras);
1105 }
1106
1107 // combo view callbacks
1108
1109 /**
1110 * callback from ComboPage when clear history is requested
1111 */
1112 public void onRemoveParentChildRelationships() {
1113 mTabControl.removeParentChildRelationShips();
1114 }
1115
1116 /**
1117 * callback from ComboPage when bookmark/history selection
1118 */
1119 @Override
1120 public void onUrlSelected(String url, boolean newTab) {
1121 removeComboView();
1122 if (!TextUtils.isEmpty(url)) {
1123 if (newTab) {
1124 openTab(url, false);
1125 } else {
1126 final Tab currentTab = mTabControl.getCurrentTab();
1127 dismissSubWindow(currentTab);
1128 loadUrl(getCurrentTopWebView(), url);
1129 }
1130 }
1131 }
1132
1133 /**
1134 * callback from ComboPage when dismissed
1135 */
1136 @Override
1137 public void onComboCanceled() {
1138 removeComboView();
1139 }
1140
1141 /**
1142 * dismiss the ComboPage
1143 */
1144 @Override
1145 public void removeComboView() {
1146 mUi.hideComboView();
1147 }
1148
1149 // active tabs page handling
1150
1151 protected void showActiveTabsPage() {
1152 mMenuState = EMPTY_MENU;
1153 mUi.showActiveTabsPage();
1154 }
1155
1156 /**
1157 * Remove the active tabs page.
1158 * @param needToAttach If true, the active tabs page did not attach a tab
1159 * to the content view, so we need to do that here.
1160 */
1161 @Override
1162 public void removeActiveTabsPage(boolean needToAttach) {
1163 mMenuState = R.id.MAIN_MENU;
1164 mUi.removeActiveTabsPage();
1165 if (needToAttach) {
1166 setActiveTab(mTabControl.getCurrentTab());
1167 }
1168 getCurrentTopWebView().requestFocus();
1169 }
1170
1171 // key handling
1172 protected void onBackKey() {
1173 if (!mUi.onBackKey()) {
1174 WebView subwindow = mTabControl.getCurrentSubWindow();
1175 if (subwindow != null) {
1176 if (subwindow.canGoBack()) {
1177 subwindow.goBack();
1178 } else {
1179 dismissSubWindow(mTabControl.getCurrentTab());
1180 }
1181 } else {
1182 goBackOnePageOrQuit();
1183 }
1184 }
1185 }
1186
1187 // menu handling and state
1188 // TODO: maybe put into separate handler
1189
1190 protected boolean onCreateOptionsMenu(Menu menu) {
1191 MenuInflater inflater = mActivity.getMenuInflater();
1192 inflater.inflate(R.menu.browser, menu);
1193 updateInLoadMenuItems(menu);
1194 // hold on to the menu reference here; it is used by the page callbacks
1195 // to update the menu based on loading state
1196 mCachedMenu = menu;
1197 return true;
1198 }
1199
1200 protected void onCreateContextMenu(ContextMenu menu, View v,
1201 ContextMenuInfo menuInfo) {
1202 if (v instanceof TitleBarBase) {
1203 return;
1204 }
1205 if (!(v instanceof WebView)) {
1206 return;
1207 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001208 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001209 WebView.HitTestResult result = webview.getHitTestResult();
1210 if (result == null) {
1211 return;
1212 }
1213
1214 int type = result.getType();
1215 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1216 Log.w(LOGTAG,
1217 "We should not show context menu when nothing is touched");
1218 return;
1219 }
1220 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1221 // let TextView handles context menu
1222 return;
1223 }
1224
1225 // Note, http://b/issue?id=1106666 is requesting that
1226 // an inflated menu can be used again. This is not available
1227 // yet, so inflate each time (yuk!)
1228 MenuInflater inflater = mActivity.getMenuInflater();
1229 inflater.inflate(R.menu.browsercontext, menu);
1230
1231 // Show the correct menu group
1232 final String extra = result.getExtra();
1233 menu.setGroupVisible(R.id.PHONE_MENU,
1234 type == WebView.HitTestResult.PHONE_TYPE);
1235 menu.setGroupVisible(R.id.EMAIL_MENU,
1236 type == WebView.HitTestResult.EMAIL_TYPE);
1237 menu.setGroupVisible(R.id.GEO_MENU,
1238 type == WebView.HitTestResult.GEO_TYPE);
1239 menu.setGroupVisible(R.id.IMAGE_MENU,
1240 type == WebView.HitTestResult.IMAGE_TYPE
1241 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1242 menu.setGroupVisible(R.id.ANCHOR_MENU,
1243 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1244 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001245 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1246 || type == WebView.HitTestResult.PHONE_TYPE
1247 || type == WebView.HitTestResult.EMAIL_TYPE
1248 || type == WebView.HitTestResult.GEO_TYPE;
1249 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1250 if (hitText) {
1251 menu.findItem(R.id.select_text_menu_id)
1252 .setOnMenuItemClickListener(new SelectText(webview));
1253 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001254 // Setup custom handling depending on the type
1255 switch (type) {
1256 case WebView.HitTestResult.PHONE_TYPE:
1257 menu.setHeaderTitle(Uri.decode(extra));
1258 menu.findItem(R.id.dial_context_menu_id).setIntent(
1259 new Intent(Intent.ACTION_VIEW, Uri
1260 .parse(WebView.SCHEME_TEL + extra)));
1261 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1262 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1263 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1264 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1265 addIntent);
1266 menu.findItem(R.id.copy_phone_context_menu_id)
1267 .setOnMenuItemClickListener(
1268 new Copy(extra));
1269 break;
1270
1271 case WebView.HitTestResult.EMAIL_TYPE:
1272 menu.setHeaderTitle(extra);
1273 menu.findItem(R.id.email_context_menu_id).setIntent(
1274 new Intent(Intent.ACTION_VIEW, Uri
1275 .parse(WebView.SCHEME_MAILTO + extra)));
1276 menu.findItem(R.id.copy_mail_context_menu_id)
1277 .setOnMenuItemClickListener(
1278 new Copy(extra));
1279 break;
1280
1281 case WebView.HitTestResult.GEO_TYPE:
1282 menu.setHeaderTitle(extra);
1283 menu.findItem(R.id.map_context_menu_id).setIntent(
1284 new Intent(Intent.ACTION_VIEW, Uri
1285 .parse(WebView.SCHEME_GEO
1286 + URLEncoder.encode(extra))));
1287 menu.findItem(R.id.copy_geo_context_menu_id)
1288 .setOnMenuItemClickListener(
1289 new Copy(extra));
1290 break;
1291
1292 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1293 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1294 TextView titleView = (TextView) LayoutInflater.from(mActivity)
1295 .inflate(android.R.layout.browser_link_context_header,
1296 null);
1297 titleView.setText(extra);
1298 menu.setHeaderView(titleView);
1299 // decide whether to show the open link in new tab option
1300 boolean showNewTab = mTabControl.canCreateNewTab();
1301 MenuItem newTabItem
1302 = menu.findItem(R.id.open_newtab_context_menu_id);
1303 newTabItem.setVisible(showNewTab);
1304 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001305 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1306 newTabItem.setOnMenuItemClickListener(
1307 new MenuItem.OnMenuItemClickListener() {
1308 @Override
1309 public boolean onMenuItemClick(MenuItem item) {
1310 final HashMap<String, WebView> hrefMap =
1311 new HashMap<String, WebView>();
1312 hrefMap.put("webview", webview);
1313 final Message msg = mHandler.obtainMessage(
1314 FOCUS_NODE_HREF,
1315 R.id.open_newtab_context_menu_id,
1316 0, hrefMap);
1317 webview.requestFocusNodeHref(msg);
1318 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001319 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001320 });
1321 } else {
1322 newTabItem.setOnMenuItemClickListener(
1323 new MenuItem.OnMenuItemClickListener() {
1324 @Override
1325 public boolean onMenuItemClick(MenuItem item) {
1326 final Tab parent = mTabControl.getCurrentTab();
1327 final Tab newTab = openTab(extra, false);
1328 if (newTab != parent) {
1329 parent.addChildTab(newTab);
1330 }
1331 return true;
1332 }
1333 });
1334 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001335 }
1336 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1337 Bookmarks.urlHasAcceptableScheme(extra));
1338 PackageManager pm = mActivity.getPackageManager();
1339 Intent send = new Intent(Intent.ACTION_SEND);
1340 send.setType("text/plain");
1341 ResolveInfo ri = pm.resolveActivity(send,
1342 PackageManager.MATCH_DEFAULT_ONLY);
1343 menu.findItem(R.id.share_link_context_menu_id)
1344 .setVisible(ri != null);
1345 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1346 break;
1347 }
1348 // otherwise fall through to handle image part
1349 case WebView.HitTestResult.IMAGE_TYPE:
1350 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1351 menu.setHeaderTitle(extra);
1352 }
1353 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1354 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1355 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001356 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001357 menu.findItem(R.id.set_wallpaper_context_menu_id).
1358 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1359 extra));
1360 break;
1361
1362 default:
1363 Log.w(LOGTAG, "We should not get here.");
1364 break;
1365 }
1366 //update the ui
1367 mUi.onContextMenuCreated(menu);
1368 }
1369
1370 /**
1371 * As the menu can be open when loading state changes
1372 * we must manually update the state of the stop/reload menu
1373 * item
1374 */
1375 private void updateInLoadMenuItems(Menu menu) {
1376 if (menu == null) {
1377 return;
1378 }
1379 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1380 MenuItem src = mInLoad ?
1381 menu.findItem(R.id.stop_menu_id):
1382 menu.findItem(R.id.reload_menu_id);
1383 if (src != null) {
1384 dest.setIcon(src.getIcon());
1385 dest.setTitle(src.getTitle());
1386 }
1387 }
1388
1389 boolean prepareOptionsMenu(Menu menu) {
1390 // This happens when the user begins to hold down the menu key, so
1391 // allow them to chord to get a shortcut.
1392 mCanChord = true;
1393 // Note: setVisible will decide whether an item is visible; while
1394 // setEnabled() will decide whether an item is enabled, which also means
1395 // whether the matching shortcut key will function.
1396 switch (mMenuState) {
1397 case EMPTY_MENU:
1398 if (mCurrentMenuState != mMenuState) {
1399 menu.setGroupVisible(R.id.MAIN_MENU, false);
1400 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1401 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1402 }
1403 break;
1404 default:
1405 if (mCurrentMenuState != mMenuState) {
1406 menu.setGroupVisible(R.id.MAIN_MENU, true);
1407 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1408 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1409 }
1410 final WebView w = getCurrentTopWebView();
1411 boolean canGoBack = false;
1412 boolean canGoForward = false;
1413 boolean isHome = false;
1414 if (w != null) {
1415 canGoBack = w.canGoBack();
1416 canGoForward = w.canGoForward();
1417 isHome = mSettings.getHomePage().equals(w.getUrl());
1418 }
1419 final MenuItem back = menu.findItem(R.id.back_menu_id);
1420 back.setEnabled(canGoBack);
1421
1422 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1423 home.setEnabled(!isHome);
1424
1425 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1426 forward.setEnabled(canGoForward);
1427
1428 // decide whether to show the share link option
1429 PackageManager pm = mActivity.getPackageManager();
1430 Intent send = new Intent(Intent.ACTION_SEND);
1431 send.setType("text/plain");
1432 ResolveInfo ri = pm.resolveActivity(send,
1433 PackageManager.MATCH_DEFAULT_ONLY);
1434 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1435
1436 boolean isNavDump = mSettings.isNavDump();
1437 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1438 nav.setVisible(isNavDump);
1439 nav.setEnabled(isNavDump);
1440
1441 boolean showDebugSettings = mSettings.showDebugSettings();
1442 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1443 counter.setVisible(showDebugSettings);
1444 counter.setEnabled(showDebugSettings);
1445
1446 // allow the ui to adjust state based settings
1447 mUi.onPrepareOptionsMenu(menu);
1448
1449 break;
1450 }
1451 mCurrentMenuState = mMenuState;
1452 return true;
1453 }
1454
1455 public boolean onOptionsItemSelected(MenuItem item) {
1456 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1457 // menu remains active, so ensure comboview is dismissed
1458 // if main menu option is selected
1459 removeComboView();
1460 }
1461 // check the action bar button before mCanChord check, as the prepare call
1462 // doesn't come for action bar buttons
1463 if (item.getItemId() == R.id.newtab) {
1464 openTabToHomePage();
1465 return true;
1466 }
1467 if (!mCanChord) {
1468 // The user has already fired a shortcut with this hold down of the
1469 // menu key.
1470 return false;
1471 }
1472 if (null == getCurrentTopWebView()) {
1473 return false;
1474 }
1475 if (mMenuIsDown) {
1476 // The shortcut action consumes the MENU. Even if it is still down,
1477 // it won't trigger the next shortcut action. In the case of the
1478 // shortcut action triggering a new activity, like Bookmarks, we
1479 // won't get onKeyUp for MENU. So it is important to reset it here.
1480 mMenuIsDown = false;
1481 }
1482 switch (item.getItemId()) {
1483 // -- Main menu
1484 case R.id.new_tab_menu_id:
1485 openTabToHomePage();
1486 break;
1487
1488 case R.id.incognito_menu_id:
1489 openIncognitoTab();
1490 break;
1491
1492 case R.id.goto_menu_id:
1493 editUrl();
1494 break;
1495
1496 case R.id.bookmarks_menu_id:
1497 bookmarksOrHistoryPicker(false);
1498 break;
1499
1500 case R.id.active_tabs_menu_id:
1501 showActiveTabsPage();
1502 break;
1503
1504 case R.id.add_bookmark_menu_id:
1505 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1506 break;
1507
1508 case R.id.stop_reload_menu_id:
1509 if (mInLoad) {
1510 stopLoading();
1511 } else {
1512 getCurrentTopWebView().reload();
1513 }
1514 break;
1515
1516 case R.id.back_menu_id:
1517 getCurrentTopWebView().goBack();
1518 break;
1519
1520 case R.id.forward_menu_id:
1521 getCurrentTopWebView().goForward();
1522 break;
1523
1524 case R.id.close_menu_id:
1525 // Close the subwindow if it exists.
1526 if (mTabControl.getCurrentSubWindow() != null) {
1527 dismissSubWindow(mTabControl.getCurrentTab());
1528 break;
1529 }
1530 closeCurrentTab();
1531 break;
1532
1533 case R.id.homepage_menu_id:
1534 Tab current = mTabControl.getCurrentTab();
1535 if (current != null) {
1536 dismissSubWindow(current);
1537 loadUrl(current.getWebView(), mSettings.getHomePage());
1538 }
1539 break;
1540
1541 case R.id.preferences_menu_id:
1542 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1543 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1544 getCurrentTopWebView().getUrl());
1545 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1546 break;
1547
1548 case R.id.find_menu_id:
1549 getCurrentTopWebView().showFindDialog(null);
1550 break;
1551
1552 case R.id.page_info_menu_id:
1553 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1554 false);
1555 break;
1556
1557 case R.id.classic_history_menu_id:
1558 bookmarksOrHistoryPicker(true);
1559 break;
1560
1561 case R.id.title_bar_share_page_url:
1562 case R.id.share_page_menu_id:
1563 Tab currentTab = mTabControl.getCurrentTab();
1564 if (null == currentTab) {
1565 mCanChord = false;
1566 return false;
1567 }
1568 currentTab.populatePickerData();
1569 sharePage(mActivity, currentTab.getTitle(),
1570 currentTab.getUrl(), currentTab.getFavicon(),
1571 createScreenshot(currentTab.getWebView(),
1572 getDesiredThumbnailWidth(mActivity),
1573 getDesiredThumbnailHeight(mActivity)));
1574 break;
1575
1576 case R.id.dump_nav_menu_id:
1577 getCurrentTopWebView().debugDump();
1578 break;
1579
1580 case R.id.dump_counters_menu_id:
1581 getCurrentTopWebView().dumpV8Counters();
1582 break;
1583
1584 case R.id.zoom_in_menu_id:
1585 getCurrentTopWebView().zoomIn();
1586 break;
1587
1588 case R.id.zoom_out_menu_id:
1589 getCurrentTopWebView().zoomOut();
1590 break;
1591
1592 case R.id.view_downloads_menu_id:
1593 viewDownloads();
1594 break;
1595
1596 case R.id.window_one_menu_id:
1597 case R.id.window_two_menu_id:
1598 case R.id.window_three_menu_id:
1599 case R.id.window_four_menu_id:
1600 case R.id.window_five_menu_id:
1601 case R.id.window_six_menu_id:
1602 case R.id.window_seven_menu_id:
1603 case R.id.window_eight_menu_id:
1604 {
1605 int menuid = item.getItemId();
1606 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1607 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1608 Tab desiredTab = mTabControl.getTab(id);
1609 if (desiredTab != null &&
1610 desiredTab != mTabControl.getCurrentTab()) {
1611 switchToTab(id);
1612 }
1613 break;
1614 }
1615 }
1616 }
1617 break;
1618
1619 default:
1620 return false;
1621 }
1622 mCanChord = false;
1623 return true;
1624 }
1625
1626 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001627 // Let the History and Bookmark fragments handle menus they created.
1628 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1629 return false;
1630 }
1631
Michael Kolb8233fac2010-10-26 16:08:53 -07001632 // chording is not an issue with context menus, but we use the same
1633 // options selector, so set mCanChord to true so we can access them.
1634 mCanChord = true;
1635 int id = item.getItemId();
1636 boolean result = true;
1637 switch (id) {
1638 // For the context menu from the title bar
1639 case R.id.title_bar_copy_page_url:
1640 Tab currentTab = mTabControl.getCurrentTab();
1641 if (null == currentTab) {
1642 result = false;
1643 break;
1644 }
1645 WebView mainView = currentTab.getWebView();
1646 if (null == mainView) {
1647 result = false;
1648 break;
1649 }
1650 copy(mainView.getUrl());
1651 break;
1652 // -- Browser context menu
1653 case R.id.open_context_menu_id:
1654 case R.id.bookmark_context_menu_id:
1655 case R.id.save_link_context_menu_id:
1656 case R.id.share_link_context_menu_id:
1657 case R.id.copy_link_context_menu_id:
1658 final WebView webView = getCurrentTopWebView();
1659 if (null == webView) {
1660 result = false;
1661 break;
1662 }
1663 final HashMap<String, WebView> hrefMap =
1664 new HashMap<String, WebView>();
1665 hrefMap.put("webview", webView);
1666 final Message msg = mHandler.obtainMessage(
1667 FOCUS_NODE_HREF, id, 0, hrefMap);
1668 webView.requestFocusNodeHref(msg);
1669 break;
1670
1671 default:
1672 // For other context menus
1673 result = onOptionsItemSelected(item);
1674 }
1675 mCanChord = false;
1676 return result;
1677 }
1678
1679 /**
1680 * support programmatically opening the context menu
1681 */
1682 public void openContextMenu(View view) {
1683 mActivity.openContextMenu(view);
1684 }
1685
1686 /**
1687 * programmatically open the options menu
1688 */
1689 public void openOptionsMenu() {
1690 mActivity.openOptionsMenu();
1691 }
1692
1693 public boolean onMenuOpened(int featureId, Menu menu) {
1694 if (mOptionsMenuOpen) {
1695 if (mConfigChanged) {
1696 // We do not need to make any changes to the state of the
1697 // title bar, since the only thing that happened was a
1698 // change in orientation
1699 mConfigChanged = false;
1700 } else {
1701 if (!mExtendedMenuOpen) {
1702 mExtendedMenuOpen = true;
1703 mUi.onExtendedMenuOpened();
1704 } else {
1705 // Switching the menu back to icon view, so show the
1706 // title bar once again.
1707 mExtendedMenuOpen = false;
1708 mUi.onExtendedMenuClosed(mInLoad);
1709 mUi.onOptionsMenuOpened();
1710 }
1711 }
1712 } else {
1713 // The options menu is closed, so open it, and show the title
1714 mOptionsMenuOpen = true;
1715 mConfigChanged = false;
1716 mExtendedMenuOpen = false;
1717 mUi.onOptionsMenuOpened();
1718 }
1719 return true;
1720 }
1721
1722 public void onOptionsMenuClosed(Menu menu) {
1723 mOptionsMenuOpen = false;
1724 mUi.onOptionsMenuClosed(mInLoad);
1725 }
1726
1727 public void onContextMenuClosed(Menu menu) {
1728 mUi.onContextMenuClosed(menu, mInLoad);
1729 }
1730
1731 // Helper method for getting the top window.
1732 @Override
1733 public WebView getCurrentTopWebView() {
1734 return mTabControl.getCurrentTopWebView();
1735 }
1736
1737 @Override
1738 public WebView getCurrentWebView() {
1739 return mTabControl.getCurrentWebView();
1740 }
1741
1742 /*
1743 * This method is called as a result of the user selecting the options
1744 * menu to see the download window. It shows the download window on top of
1745 * the current window.
1746 */
1747 void viewDownloads() {
1748 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1749 mActivity.startActivity(intent);
1750 }
1751
1752 // action mode
1753
1754 void onActionModeStarted(ActionMode mode) {
1755 mUi.onActionModeStarted(mode);
1756 mActionMode = mode;
1757 }
1758
1759 /*
1760 * True if a custom ActionMode (i.e. find or select) is in use.
1761 */
1762 @Override
1763 public boolean isInCustomActionMode() {
1764 return mActionMode != null;
1765 }
1766
1767 /*
1768 * End the current ActionMode.
1769 */
1770 @Override
1771 public void endActionMode() {
1772 if (mActionMode != null) {
1773 mActionMode.finish();
1774 }
1775 }
1776
1777 /*
1778 * Called by find and select when they are finished. Replace title bars
1779 * as necessary.
1780 */
1781 public void onActionModeFinished(ActionMode mode) {
1782 if (!isInCustomActionMode()) return;
1783 mUi.onActionModeFinished(mInLoad);
1784 mActionMode = null;
1785 }
1786
1787 boolean isInLoad() {
1788 return mInLoad;
1789 }
1790
1791 // bookmark handling
1792
1793 /**
1794 * add the current page as a bookmark to the given folder id
1795 * @param folderId use -1 for the default folder
1796 */
1797 @Override
1798 public void bookmarkCurrentPage(long folderId) {
1799 Intent i = new Intent(mActivity,
1800 AddBookmarkPage.class);
1801 WebView w = getCurrentTopWebView();
1802 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1803 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1804 String touchIconUrl = w.getTouchIconUrl();
1805 if (touchIconUrl != null) {
1806 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1807 WebSettings settings = w.getSettings();
1808 if (settings != null) {
1809 i.putExtra(AddBookmarkPage.USER_AGENT,
1810 settings.getUserAgentString());
1811 }
1812 }
1813 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1814 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1815 getDesiredThumbnailHeight(mActivity)));
1816 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1817 i.putExtra(BrowserContract.Bookmarks.PARENT,
1818 folderId);
1819 // Put the dialog at the upper right of the screen, covering the
1820 // star on the title bar.
1821 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1822 mActivity.startActivity(i);
1823 }
1824
1825 // file chooser
1826 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1827 mUploadHandler = new UploadHandler(this);
1828 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1829 }
1830
1831 // thumbnails
1832
1833 /**
1834 * Return the desired width for thumbnail screenshots, which are stored in
1835 * the database, and used on the bookmarks screen.
1836 * @param context Context for finding out the density of the screen.
1837 * @return desired width for thumbnail screenshot.
1838 */
1839 static int getDesiredThumbnailWidth(Context context) {
1840 return context.getResources().getDimensionPixelOffset(
1841 R.dimen.bookmarkThumbnailWidth);
1842 }
1843
1844 /**
1845 * Return the desired height 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 height for thumbnail screenshot.
1849 */
1850 static int getDesiredThumbnailHeight(Context context) {
1851 return context.getResources().getDimensionPixelOffset(
1852 R.dimen.bookmarkThumbnailHeight);
1853 }
1854
1855 private static Bitmap createScreenshot(WebView view, int width, int height) {
1856 Picture thumbnail = view.capturePicture();
1857 if (thumbnail == null) {
1858 return null;
1859 }
1860 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1861 Canvas canvas = new Canvas(bm);
1862 // May need to tweak these values to determine what is the
1863 // best scale factor
1864 int thumbnailWidth = thumbnail.getWidth();
1865 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001866 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001867 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001868 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001869 } else {
1870 return null;
1871 }
John Reckfe49ab42010-11-16 17:09:37 -08001872
Michael Kolb8233fac2010-10-26 16:08:53 -07001873 if (view.getWidth() > view.getHeight() &&
1874 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1875 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001876 // than the height of the view, center the thumnail and crop the sides
1877 scaleFactor = (float) height / (float)thumbnailHeight;
1878 float wx = (thumbnailWidth * scaleFactor) - width;
1879 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001880 }
1881
John Reckfe49ab42010-11-16 17:09:37 -08001882 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001883
1884 thumbnail.draw(canvas);
1885 return bm;
1886 }
1887
1888 private void updateScreenshot(WebView view) {
1889 // If this is a bookmarked site, add a screenshot to the database.
1890 // FIXME: When should we update? Every time?
1891 // FIXME: Would like to make sure there is actually something to
1892 // draw, but the API for that (WebViewCore.pictureReady()) is not
1893 // currently accessible here.
1894
1895 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1896 getDesiredThumbnailHeight(mActivity));
1897 if (bm == null) {
1898 return;
1899 }
1900
1901 final ContentResolver cr = mActivity.getContentResolver();
1902 final String url = view.getUrl();
1903 final String originalUrl = view.getOriginalUrl();
1904
1905 new AsyncTask<Void, Void, Void>() {
1906 @Override
1907 protected Void doInBackground(Void... unused) {
1908 Cursor cursor = null;
1909 try {
1910 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1911 if (cursor != null && cursor.moveToFirst()) {
1912 final ByteArrayOutputStream os =
1913 new ByteArrayOutputStream();
1914 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
1915
1916 ContentValues values = new ContentValues();
1917 values.put(Images.THUMBNAIL, os.toByteArray());
1918 values.put(Images.URL, cursor.getString(0));
1919
1920 do {
1921 cr.update(Images.CONTENT_URI, values, null, null);
1922 } while (cursor.moveToNext());
1923 }
1924 } catch (IllegalStateException e) {
1925 // Ignore
1926 } finally {
1927 if (cursor != null) cursor.close();
1928 }
1929 return null;
1930 }
1931 }.execute();
1932 }
1933
1934 private class Copy implements OnMenuItemClickListener {
1935 private CharSequence mText;
1936
1937 public boolean onMenuItemClick(MenuItem item) {
1938 copy(mText);
1939 return true;
1940 }
1941
1942 public Copy(CharSequence toCopy) {
1943 mText = toCopy;
1944 }
1945 }
1946
Leon Scroggins63c02662010-11-18 15:16:27 -05001947 private static class Download implements OnMenuItemClickListener {
1948 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001949 private String mText;
1950
1951 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001952 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1953 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001954 return true;
1955 }
1956
Leon Scroggins63c02662010-11-18 15:16:27 -05001957 public Download(Activity activity, String toDownload) {
1958 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001959 mText = toDownload;
1960 }
1961 }
1962
Cary Clark8974d282010-11-22 10:46:05 -05001963 private static class SelectText implements OnMenuItemClickListener {
1964 private WebView mWebView;
1965
1966 public boolean onMenuItemClick(MenuItem item) {
1967 if (mWebView != null) {
1968 return mWebView.selectText();
1969 }
1970 return false;
1971 }
1972
1973 public SelectText(WebView webView) {
1974 mWebView = webView;
1975 }
1976
1977 }
1978
Michael Kolb8233fac2010-10-26 16:08:53 -07001979 /********************** TODO: UI stuff *****************************/
1980
1981 // these methods have been copied, they still need to be cleaned up
1982
1983 /****************** tabs ***************************************************/
1984
1985 // basic tab interactions:
1986
1987 // it is assumed that tabcontrol already knows about the tab
1988 protected void addTab(Tab tab) {
1989 mUi.addTab(tab);
1990 }
1991
1992 protected void removeTab(Tab tab) {
1993 mUi.removeTab(tab);
1994 mTabControl.removeTab(tab);
1995 }
1996
1997 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001998 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08001999 // the tab is guaranteed to have a webview after setCurrentTab
2000 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002001 }
2002
2003 protected void closeEmptyChildTab() {
2004 Tab current = mTabControl.getCurrentTab();
2005 if (current != null
2006 && current.getWebView().copyBackForwardList().getSize() == 0) {
2007 Tab parent = current.getParentTab();
2008 if (parent != null) {
2009 switchToTab(mTabControl.getTabIndex(parent));
2010 closeTab(current);
2011 }
2012 }
2013 }
2014
2015 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
2016 Log.i(LOGTAG, "Reusing tab for " + appId);
2017 // Dismiss the subwindow if applicable.
2018 dismissSubWindow(appTab);
2019 // Since we might kill the WebView, remove it from the
2020 // content view first.
2021 mUi.detachTab(appTab);
2022 // Recreate the main WebView after destroying the old one.
2023 // If the WebView has the same original url and is on that
2024 // page, it can be reused.
2025 boolean needsLoad =
2026 mTabControl.recreateWebView(appTab, urlData);
2027 // TODO: analyze why the remove and add are necessary
2028 mUi.attachTab(appTab);
2029 if (mTabControl.getCurrentTab() != appTab) {
2030 switchToTab(mTabControl.getTabIndex(appTab));
2031 if (needsLoad) {
2032 loadUrlDataIn(appTab, urlData);
2033 }
2034 } else {
2035 // If the tab was the current tab, we have to attach
2036 // it to the view system again.
2037 setActiveTab(appTab);
2038 if (needsLoad) {
2039 loadUrlDataIn(appTab, urlData);
2040 }
2041 }
2042 }
2043
2044 // Remove the sub window if it exists. Also called by TabControl when the
2045 // user clicks the 'X' to dismiss a sub window.
2046 public void dismissSubWindow(Tab tab) {
2047 removeSubWindow(tab);
2048 // dismiss the subwindow. This will destroy the WebView.
2049 tab.dismissSubWindow();
2050 getCurrentTopWebView().requestFocus();
2051 }
2052
2053 @Override
2054 public void removeSubWindow(Tab t) {
2055 if (t.getSubWebView() != null) {
2056 mUi.removeSubWindow(t.getSubViewContainer());
2057 }
2058 }
2059
2060 @Override
2061 public void attachSubWindow(Tab tab) {
2062 if (tab.getSubWebView() != null) {
2063 mUi.attachSubWindow(tab.getSubViewContainer());
2064 getCurrentTopWebView().requestFocus();
2065 }
2066 }
2067
2068 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
2069 // that accepts url as string.
2070
2071 protected Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
2072 return openTabAndShow(new UrlData(url), closeOnExit, appId);
2073 }
2074
2075 // This method does a ton of stuff. It will attempt to create a new tab
2076 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2077 // url isn't null, it will load the given url.
2078
2079 public Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
2080 String appId) {
2081 final Tab currentTab = mTabControl.getCurrentTab();
2082 if (mTabControl.canCreateNewTab()) {
2083 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
2084 urlData.mUrl, false);
2085 WebView webview = tab.getWebView();
2086 // We must set the new tab as the current tab to reflect the old
2087 // animation behavior.
2088 addTab(tab);
2089 setActiveTab(tab);
2090 if (!urlData.isEmpty()) {
2091 loadUrlDataIn(tab, urlData);
2092 }
2093 return tab;
2094 } else {
2095 // Get rid of the subwindow if it exists
2096 dismissSubWindow(currentTab);
2097 if (!urlData.isEmpty()) {
2098 // Load the given url.
2099 loadUrlDataIn(currentTab, urlData);
2100 }
2101 return currentTab;
2102 }
2103 }
2104
2105 protected Tab openTab(String url, boolean forceForeground) {
2106 if (mSettings.openInBackground() && !forceForeground) {
2107 Tab tab = mTabControl.createNewTab();
2108 if (tab != null) {
2109 addTab(tab);
2110 WebView view = tab.getWebView();
2111 loadUrl(view, url);
2112 }
2113 return tab;
2114 } else {
2115 return openTabAndShow(url, false, null);
2116 }
2117 }
2118
2119 @Override
2120 public Tab openIncognitoTab() {
2121 if (mTabControl.canCreateNewTab()) {
2122 Tab currentTab = mTabControl.getCurrentTab();
2123 Tab tab = mTabControl.createNewTab(false, null, null, true);
2124 addTab(tab);
2125 setActiveTab(tab);
2126 return tab;
2127 }
2128 return null;
2129 }
2130
2131 /**
2132 * @param index Index of the tab to change to, as defined by
2133 * mTabControl.getTabIndex(Tab t).
2134 * @return boolean True if we successfully switched to a different tab. If
2135 * the indexth tab is null, or if that tab is the same as
2136 * the current one, return false.
2137 */
2138 @Override
2139 public boolean switchToTab(int index) {
2140 Tab tab = mTabControl.getTab(index);
2141 Tab currentTab = mTabControl.getCurrentTab();
2142 if (tab == null || tab == currentTab) {
2143 return false;
2144 }
2145 setActiveTab(tab);
2146 return true;
2147 }
2148
2149 @Override
2150 public Tab openTabToHomePage() {
2151 return openTabAndShow(mSettings.getHomePage(), false, null);
2152 }
2153
2154 @Override
2155 public void closeCurrentTab() {
2156 final Tab current = mTabControl.getCurrentTab();
2157 if (mTabControl.getTabCount() == 1) {
2158 // This is the last tab. Open a new one, with the home
2159 // page and close the current one.
2160 openTabToHomePage();
2161 closeTab(current);
2162 return;
2163 }
2164 final Tab parent = current.getParentTab();
2165 int indexToShow = -1;
2166 if (parent != null) {
2167 indexToShow = mTabControl.getTabIndex(parent);
2168 } else {
2169 final int currentIndex = mTabControl.getCurrentIndex();
2170 // Try to move to the tab to the right
2171 indexToShow = currentIndex + 1;
2172 if (indexToShow > mTabControl.getTabCount() - 1) {
2173 // Try to move to the tab to the left
2174 indexToShow = currentIndex - 1;
2175 }
2176 }
2177 if (switchToTab(indexToShow)) {
2178 // Close window
2179 closeTab(current);
2180 }
2181 }
2182
2183 /**
2184 * Close the tab, remove its associated title bar, and adjust mTabControl's
2185 * current tab to a valid value.
2186 */
2187 @Override
2188 public void closeTab(Tab tab) {
2189 int currentIndex = mTabControl.getCurrentIndex();
2190 int removeIndex = mTabControl.getTabIndex(tab);
2191 removeTab(tab);
2192 if (currentIndex >= removeIndex && currentIndex != 0) {
2193 currentIndex--;
2194 }
2195 Tab newtab = mTabControl.getTab(currentIndex);
2196 setActiveTab(newtab);
2197 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
Steve Block83101a82010-11-26 11:33:35 +00002198 WebView.cleanupPrivateBrowsingFiles();
Michael Kolb8233fac2010-10-26 16:08:53 -07002199 }
2200 }
2201
2202 /**************** TODO: Url loading clean up *******************************/
2203
2204 // Called when loading from context menu or LOAD_URL message
2205 protected void loadUrlFromContext(WebView view, String url) {
2206 // In case the user enters nothing.
2207 if (url != null && url.length() != 0 && view != null) {
2208 url = UrlUtils.smartUrlFilter(url);
2209 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2210 loadUrl(view, url);
2211 }
2212 }
2213 }
2214
2215 /**
2216 * Load the URL into the given WebView and update the title bar
2217 * to reflect the new load. Call this instead of WebView.loadUrl
2218 * directly.
2219 * @param view The WebView used to load url.
2220 * @param url The URL to load.
2221 */
2222 protected void loadUrl(WebView view, String url) {
2223 updateTitleBarForNewLoad(view, url);
2224 view.loadUrl(url);
2225 }
2226
2227 /**
2228 * Load UrlData into a Tab and update the title bar to reflect the new
2229 * load. Call this instead of UrlData.loadIn directly.
2230 * @param t The Tab used to load.
2231 * @param data The UrlData being loaded.
2232 */
2233 protected void loadUrlDataIn(Tab t, UrlData data) {
2234 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
2235 data.loadIn(t);
2236 }
2237
2238 /**
2239 * Resets the browser title-view to whatever it must be
2240 * (for example, if we had a loading error)
2241 * When we have a new page, we call resetTitle, when we
2242 * have to reset the titlebar to whatever it used to be
2243 * (for example, if the user chose to stop loading), we
2244 * call resetTitleAndRevertLockIcon.
2245 */
2246 public void resetTitleAndRevertLockIcon(Tab tab) {
2247 mUi.resetTitleAndRevertLockIcon(tab);
2248 }
2249
2250 void resetTitleAndIcon(Tab tab) {
2251 mUi.resetTitleAndIcon(tab);
2252 }
2253
2254 /**
2255 * If the WebView is the top window, update the title bar to reflect
2256 * loading the new URL. i.e. set its text, clear the favicon (which
2257 * will be set once the page begins loading), and set the progress to
2258 * INITIAL_PROGRESS to show that the page has begun to load. Called
2259 * by loadUrl and loadUrlDataIn.
2260 * @param view The WebView that is starting a load.
2261 * @param url The URL that is being loaded.
2262 */
2263 private void updateTitleBarForNewLoad(WebView view, String url) {
2264 if (view == getCurrentTopWebView()) {
2265 // TODO we should come with a tab and not with a view
2266 Tab tab = mTabControl.getTabFromView(view);
2267 setUrlTitle(tab, url, null);
2268 mUi.setFavicon(tab, null);
2269 onProgressChanged(tab, INITIAL_PROGRESS);
2270 }
2271 }
2272
2273 /**
2274 * Sets a title composed of the URL and the title string.
2275 * @param url The URL of the site being loaded.
2276 * @param title The title of the site being loaded.
2277 */
2278 void setUrlTitle(Tab tab, String url, String title) {
2279 tab.setCurrentUrl(url);
2280 tab.setCurrentTitle(title);
2281 // If we are in voice search mode, the title has already been set.
2282 if (tab.isInVoiceSearchMode()) return;
2283 mUi.setUrlTitle(tab, url, title);
2284 }
2285
2286 void goBackOnePageOrQuit() {
2287 Tab current = mTabControl.getCurrentTab();
2288 if (current == null) {
2289 /*
2290 * Instead of finishing the activity, simply push this to the back
2291 * of the stack and let ActivityManager to choose the foreground
2292 * activity. As BrowserActivity is singleTask, it will be always the
2293 * root of the task. So we can use either true or false for
2294 * moveTaskToBack().
2295 */
2296 mActivity.moveTaskToBack(true);
2297 return;
2298 }
2299 WebView w = current.getWebView();
2300 if (w.canGoBack()) {
2301 w.goBack();
2302 } else {
2303 // Check to see if we are closing a window that was created by
2304 // another window. If so, we switch back to that window.
2305 Tab parent = current.getParentTab();
2306 if (parent != null) {
2307 switchToTab(mTabControl.getTabIndex(parent));
2308 // Now we close the other tab
2309 closeTab(current);
2310 } else {
2311 if (current.closeOnExit()) {
2312 // force the tab's inLoad() to be false as we are going to
2313 // either finish the activity or remove the tab. This will
2314 // ensure pauseWebViewTimers() taking action.
2315 mTabControl.getCurrentTab().clearInPageLoad();
2316 if (mTabControl.getTabCount() == 1) {
2317 mActivity.finish();
2318 return;
2319 }
2320 if (mActivityPaused) {
2321 Log.e(LOGTAG, "BrowserActivity is already paused "
2322 + "while handing goBackOnePageOrQuit.");
2323 }
2324 pauseWebViewTimers(true);
2325 removeTab(current);
2326 }
2327 /*
2328 * Instead of finishing the activity, simply push this to the back
2329 * of the stack and let ActivityManager to choose the foreground
2330 * activity. As BrowserActivity is singleTask, it will be always the
2331 * root of the task. So we can use either true or false for
2332 * moveTaskToBack().
2333 */
2334 mActivity.moveTaskToBack(true);
2335 }
2336 }
2337 }
2338
2339 /**
2340 * Feed the previously stored results strings to the BrowserProvider so that
2341 * the SearchDialog will show them instead of the standard searches.
2342 * @param result String to show on the editable line of the SearchDialog.
2343 */
2344 @Override
2345 public void showVoiceSearchResults(String result) {
2346 ContentProviderClient client = mActivity.getContentResolver()
2347 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2348 ContentProvider prov = client.getLocalContentProvider();
2349 BrowserProvider bp = (BrowserProvider) prov;
2350 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2351 client.release();
2352
2353 Bundle bundle = createGoogleSearchSourceBundle(
2354 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2355 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2356 startSearch(result, false, bundle, false);
2357 }
2358
2359 private void startSearch(String initialQuery, boolean selectInitialQuery,
2360 Bundle appSearchData, boolean globalSearch) {
2361 if (appSearchData == null) {
2362 appSearchData = createGoogleSearchSourceBundle(
2363 GOOGLE_SEARCH_SOURCE_TYPE);
2364 }
2365
2366 SearchEngine searchEngine = mSettings.getSearchEngine();
2367 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2368 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2369 }
2370 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2371 globalSearch);
2372 }
2373
2374 private Bundle createGoogleSearchSourceBundle(String source) {
2375 Bundle bundle = new Bundle();
2376 bundle.putString(Search.SOURCE, source);
2377 return bundle;
2378 }
2379
2380 /**
2381 * handle key events in browser
2382 *
2383 * @param keyCode
2384 * @param event
2385 * @return true if handled, false to pass to super
2386 */
2387 boolean onKeyDown(int keyCode, KeyEvent event) {
2388 // Even if MENU is already held down, we need to call to super to open
2389 // the IME on long press.
2390 if (KeyEvent.KEYCODE_MENU == keyCode) {
2391 mMenuIsDown = true;
2392 return false;
2393 }
2394 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2395 // still down, we don't want to trigger the search. Pretend to consume
2396 // the key and do nothing.
2397 if (mMenuIsDown) return true;
2398
2399 switch(keyCode) {
2400 case KeyEvent.KEYCODE_SPACE:
2401 // WebView/WebTextView handle the keys in the KeyDown. As
2402 // the Activity's shortcut keys are only handled when WebView
2403 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2404 if (event.isShiftPressed()) {
2405 pageUp();
2406 } else {
2407 pageDown();
2408 }
2409 return true;
2410 case KeyEvent.KEYCODE_BACK:
2411 if (event.getRepeatCount() == 0) {
2412 event.startTracking();
2413 return true;
2414 } else if (mUi.showsWeb()
2415 && event.isLongPress()) {
2416 bookmarksOrHistoryPicker(true);
2417 return true;
2418 }
2419 break;
2420 }
2421 return false;
2422 }
2423
2424 boolean onKeyUp(int keyCode, KeyEvent event) {
2425 switch(keyCode) {
2426 case KeyEvent.KEYCODE_MENU:
2427 mMenuIsDown = false;
2428 break;
2429 case KeyEvent.KEYCODE_BACK:
2430 if (event.isTracking() && !event.isCanceled()) {
2431 onBackKey();
2432 return true;
2433 }
2434 break;
2435 }
2436 return false;
2437 }
2438
2439 public boolean isMenuDown() {
2440 return mMenuIsDown;
2441 }
2442
Ben Murdoch8029a772010-11-16 11:58:21 +00002443 public void setupAutoFill(Message message) {
2444 // Open the settings activity at the AutoFill profile fragment so that
2445 // the user can create a new profile. When they return, we will dispatch
2446 // the message so that we can autofill the form using their new profile.
2447 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2448 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2449 AutoFillSettingsFragment.class.getName());
2450 mAutoFillSetupMessage = message;
2451 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2452 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002453}