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