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