blob: fe27f8da5c621555bd8b97094e76315e721762d1 [file] [log] [blame]
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2006 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 android.app.Activity;
20import android.app.ActivityManager;
21import android.app.AlertDialog;
22import android.app.SearchManager;
23import android.app.ProgressDialog;
24import android.content.ActivityNotFoundException;
25import android.content.res.AssetManager;
26import android.content.BroadcastReceiver;
27import android.content.ComponentName;
28import android.content.ContentResolver;
29import android.content.ContentValues;
30import android.content.Context;
31import android.content.DialogInterface.OnCancelListener;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.IntentFilter;
35import android.content.ServiceConnection;
36import android.content.pm.ActivityInfo;
37import android.content.pm.PackageManager;
38import android.content.pm.ResolveInfo;
39import android.content.res.Configuration;
40import android.content.res.Resources;
41import android.database.Cursor;
42import android.database.sqlite.SQLiteDatabase;
43import android.database.sqlite.SQLiteException;
44import android.graphics.Bitmap;
45import android.graphics.Canvas;
46import android.graphics.Color;
47import android.graphics.DrawFilter;
48import android.graphics.Paint;
49import android.graphics.PaintFlagsDrawFilter;
50import android.graphics.Picture;
51import android.graphics.drawable.BitmapDrawable;
52import android.graphics.drawable.Drawable;
53import android.graphics.drawable.LayerDrawable;
54import android.graphics.drawable.PaintDrawable;
55import android.hardware.SensorListener;
56import android.hardware.SensorManager;
57import android.net.ConnectivityManager;
58import android.net.NetworkInfo;
59import android.net.Uri;
60import android.net.WebAddress;
61import android.net.http.EventHandler;
62import android.net.http.RequestQueue;
63import android.net.http.SslCertificate;
64import android.net.http.SslError;
The Android Open Source Projected217d92008-12-17 18:05:52 -080065import android.os.AsyncTask;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -070066import android.os.Build;
67import android.os.Bundle;
68import android.os.Debug;
69import android.os.Environment;
70import android.os.Handler;
71import android.os.IBinder;
72import android.os.Message;
73import android.os.PowerManager;
74import android.os.Process;
75import android.os.RemoteException;
76import android.os.ServiceManager;
77import android.os.SystemClock;
78import android.os.SystemProperties;
The Android Open Source Projected217d92008-12-17 18:05:52 -080079import android.preference.PreferenceManager;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -070080import android.provider.Browser;
81import android.provider.Checkin;
82import android.provider.Contacts.Intents.Insert;
83import android.provider.Contacts;
84import android.provider.Downloads;
The Android Open Source Projected217d92008-12-17 18:05:52 -080085import android.provider.MediaStore;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -070086import android.text.IClipboard;
The Android Open Source Projected217d92008-12-17 18:05:52 -080087import android.text.TextUtils;
88import android.text.format.DateFormat;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -070089import android.text.util.Regex;
90import android.util.Config;
91import android.util.Log;
92import android.view.ContextMenu;
93import android.view.ContextMenu.ContextMenuInfo;
94import android.view.MenuItem.OnMenuItemClickListener;
95import android.view.Gravity;
96import android.view.KeyEvent;
97import android.view.LayoutInflater;
98import android.view.Menu;
99import android.view.MenuInflater;
100import android.view.MenuItem;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700101import android.view.View;
102import android.view.ViewGroup;
103import android.view.Window;
104import android.view.animation.AlphaAnimation;
105import android.view.animation.Animation;
106import android.view.animation.AnimationSet;
107import android.view.animation.AnimationUtils;
108import android.view.animation.DecelerateInterpolator;
109import android.view.animation.ScaleAnimation;
110import android.view.animation.TranslateAnimation;
111import android.webkit.CookieManager;
112import android.webkit.CookieSyncManager;
113import android.webkit.DownloadListener;
114import android.webkit.HttpAuthHandler;
115import android.webkit.JsPromptResult;
116import android.webkit.JsResult;
117import android.webkit.SslErrorHandler;
118import android.webkit.URLUtil;
119import android.webkit.WebChromeClient;
120import android.webkit.WebHistoryItem;
121import android.webkit.WebIconDatabase;
122import android.webkit.WebView;
123import android.webkit.WebViewClient;
124import android.widget.EditText;
125import android.widget.FrameLayout;
126import android.widget.LinearLayout;
127import android.widget.TextView;
128import android.widget.Toast;
129
130import com.google.android.googleapps.IGoogleLoginService;
131import com.google.android.googlelogin.GoogleLoginServiceConstants;
132
133import java.io.BufferedOutputStream;
134import java.io.File;
135import java.io.FileInputStream;
136import java.io.FileOutputStream;
137import java.io.InputStream;
138import java.io.IOException;
139import java.net.MalformedURLException;
140import java.net.URL;
141import java.net.URLEncoder;
142import java.text.ParseException;
143import java.util.Date;
144import java.util.Enumeration;
145import java.util.HashMap;
146import java.util.HashSet;
147import java.util.List;
The Android Open Source Projected217d92008-12-17 18:05:52 -0800148import java.util.Locale;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700149import java.util.regex.Matcher;
150import java.util.regex.Pattern;
151import java.util.Vector;
152import java.util.zip.ZipEntry;
153import java.util.zip.ZipFile;
154import java.util.zip.ZipInputStream;
155
156public class BrowserActivity extends Activity
157 implements KeyTracker.OnKeyTracker,
158 View.OnCreateContextMenuListener,
159 DownloadListener {
160
161 private IGoogleLoginService mGls = null;
162 private ServiceConnection mGlsConnection = null;
163
164 private SensorManager mSensorManager = null;
165
166 /* Whitelisted webpages
167 private static HashSet<String> sWhiteList;
168
169 static {
170 sWhiteList = new HashSet<String>();
171 sWhiteList.add("cnn.com/");
172 sWhiteList.add("espn.go.com/");
173 sWhiteList.add("nytimes.com/");
174 sWhiteList.add("engadget.com/");
175 sWhiteList.add("yahoo.com/");
176 sWhiteList.add("msn.com/");
177 sWhiteList.add("amazon.com/");
178 sWhiteList.add("consumerist.com/");
179 sWhiteList.add("google.com/m/news");
180 }
181 */
182
183 private void setupHomePage() {
184 final Runnable getAccount = new Runnable() {
185 public void run() {
The Android Open Source Projected217d92008-12-17 18:05:52 -0800186 // Lower priority
187 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700188 // get the default home page
189 String homepage = mSettings.getHomePage();
190
191 try {
192 if (mGls == null) return;
193
194 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
195 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
196
197 // three cases:
198 //
199 // hostedUser == googleUser
200 // The device has only a google account
201 //
202 // hostedUser != googleUser
203 // The device has a hosted account and a google account
204 //
205 // hostedUser != null, googleUser == null
206 // The device has only a hosted account (so far)
207
208 // developers might have no accounts at all
209 if (hostedUser == null) return;
210
211 if (googleUser == null || !hostedUser.equals(googleUser)) {
212 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
213 homepage = "http://www.google.com/m/a/" + domain;
214 }
215 } catch (RemoteException ignore) {
216 // Login service died; carry on
217 } catch (RuntimeException ignore) {
218 // Login service died; carry on
219 } finally {
220 finish(homepage);
221 }
222 }
223
224 private void finish(final String homepage) {
225 mHandler.post(new Runnable() {
226 public void run() {
227 mSettings.setHomePage(BrowserActivity.this, homepage);
228 resumeAfterCredentials();
229
230 // as this is running in a separate thread,
231 // BrowserActivity's onDestroy() may have been called,
232 // which also calls unbindService().
233 if (mGlsConnection != null) {
234 // we no longer need to keep GLS open
235 unbindService(mGlsConnection);
236 mGlsConnection = null;
237 }
238 } });
239 } };
240
241 final boolean[] done = { false };
242
243 // Open a connection to the Google Login Service. The first
244 // time the connection is established, set up the homepage depending on
245 // the account in a background thread.
246 mGlsConnection = new ServiceConnection() {
247 public void onServiceConnected(ComponentName className, IBinder service) {
248 mGls = IGoogleLoginService.Stub.asInterface(service);
249 if (done[0] == false) {
250 done[0] = true;
The Android Open Source Projected217d92008-12-17 18:05:52 -0800251 Thread account = new Thread(getAccount);
252 account.setName("GLSAccount");
253 account.start();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700254 }
255 }
256 public void onServiceDisconnected(ComponentName className) {
257 mGls = null;
258 }
259 };
260
261 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
262 mGlsConnection, Context.BIND_AUTO_CREATE);
263 }
264
265 /**
266 * This class is in charge of installing pre-packaged plugins
267 * from the Browser assets directory to the user's data partition.
268 * Plugins are loaded from the "plugins" directory in the assets;
269 * Anything that is in this directory will be copied over to the
270 * user data partition in app_plugins.
271 */
272 private class CopyPlugins implements Runnable {
273 final static String TAG = "PluginsInstaller";
274 final static String ZIP_FILTER = "assets/plugins/";
275 final static String APK_PATH = "/system/app/Browser.apk";
276 final static String PLUGIN_EXTENSION = ".so";
277 final static String TEMPORARY_EXTENSION = "_temp";
278 final static String BUILD_INFOS_FILE = "build.prop";
279 final static String SYSTEM_BUILD_INFOS_FILE = "/system/"
280 + BUILD_INFOS_FILE;
281 final int BUFSIZE = 4096;
282 boolean mDoOverwrite = false;
283 String pluginsPath;
284 Context mContext;
285 File pluginsDir;
286 AssetManager manager;
287
288 public CopyPlugins (boolean overwrite, Context context) {
289 mDoOverwrite = overwrite;
290 mContext = context;
291 }
292
293 /**
294 * Returned a filtered list of ZipEntry.
295 * We list all the files contained in the zip and
296 * only returns the ones starting with the ZIP_FILTER
297 * path.
298 *
299 * @param zip the zip file used.
300 */
301 public Vector<ZipEntry> pluginsFilesFromZip(ZipFile zip) {
302 Vector<ZipEntry> list = new Vector<ZipEntry>();
303 Enumeration entries = zip.entries();
304 while (entries.hasMoreElements()) {
305 ZipEntry entry = (ZipEntry) entries.nextElement();
306 if (entry.getName().startsWith(ZIP_FILTER)) {
307 list.add(entry);
308 }
309 }
310 return list;
311 }
312
313 /**
314 * Utility method to copy the content from an inputstream
315 * to a file output stream.
316 */
317 public void copyStreams(InputStream is, FileOutputStream fos) {
318 BufferedOutputStream os = null;
319 try {
320 byte data[] = new byte[BUFSIZE];
321 int count;
322 os = new BufferedOutputStream(fos, BUFSIZE);
323 while ((count = is.read(data, 0, BUFSIZE)) != -1) {
324 os.write(data, 0, count);
325 }
326 os.flush();
327 } catch (IOException e) {
328 Log.e(TAG, "Exception while copying: " + e);
329 } finally {
330 try {
331 if (os != null) {
332 os.close();
333 }
334 } catch (IOException e2) {
335 Log.e(TAG, "Exception while closing the stream: " + e2);
336 }
337 }
338 }
339
340 /**
341 * Returns a string containing the contents of a file
342 *
343 * @param file the target file
344 */
345 private String contentsOfFile(File file) {
346 String ret = null;
347 FileInputStream is = null;
348 try {
349 byte[] buffer = new byte[BUFSIZE];
350 int count;
351 is = new FileInputStream(file);
352 StringBuffer out = new StringBuffer();
353
354 while ((count = is.read(buffer, 0, BUFSIZE)) != -1) {
355 out.append(new String(buffer, 0, count));
356 }
357 ret = out.toString();
358 } catch (IOException e) {
359 Log.e(TAG, "Exception getting contents of file " + e);
360 } finally {
361 if (is != null) {
362 try {
363 is.close();
364 } catch (IOException e2) {
365 Log.e(TAG, "Exception while closing the file: " + e2);
366 }
367 }
368 }
369 return ret;
370 }
371
372 /**
373 * Utility method to initialize the user data plugins path.
374 */
375 public void initPluginsPath() {
376 BrowserSettings s = BrowserSettings.getInstance();
377 pluginsPath = s.getPluginsPath();
378 if (pluginsPath == null) {
379 s.loadFromDb(mContext);
380 pluginsPath = s.getPluginsPath();
381 }
382 if (Config.LOGV) {
383 Log.v(TAG, "Plugin path: " + pluginsPath);
384 }
385 }
386
387 /**
388 * Utility method to delete a file or a directory
389 *
390 * @param file the File to delete
391 */
392 public void deleteFile(File file) {
393 File[] files = file.listFiles();
394 if ((files != null) && files.length > 0) {
395 for (int i=0; i< files.length; i++) {
396 deleteFile(files[i]);
397 }
398 }
399 if (!file.delete()) {
400 Log.e(TAG, file.getPath() + " could not get deleted");
401 }
402 }
403
404 /**
405 * Clean the content of the plugins directory.
406 * We delete the directory, then recreate it.
407 */
408 public void cleanPluginsDirectory() {
409 if (Config.LOGV) {
410 Log.v(TAG, "delete plugins directory: " + pluginsPath);
411 }
412 File pluginsDirectory = new File(pluginsPath);
413 deleteFile(pluginsDirectory);
414 pluginsDirectory.mkdir();
415 }
416
417
418 /**
419 * Copy the SYSTEM_BUILD_INFOS_FILE file containing the
420 * informations about the system build to the
421 * BUILD_INFOS_FILE in the plugins directory.
422 */
423 public void copyBuildInfos() {
424 try {
425 if (Config.LOGV) {
426 Log.v(TAG, "Copy build infos to the plugins directory");
427 }
428 File buildInfoFile = new File(SYSTEM_BUILD_INFOS_FILE);
429 File buildInfoPlugins = new File(pluginsPath, BUILD_INFOS_FILE);
430 copyStreams(new FileInputStream(buildInfoFile),
431 new FileOutputStream(buildInfoPlugins));
432 } catch (IOException e) {
433 Log.e(TAG, "Exception while copying the build infos: " + e);
434 }
435 }
436
437 /**
438 * Returns true if the current system is newer than the
439 * system that installed the plugins.
440 * We determinate this by checking the build number of the system.
441 *
442 * At the end of the plugins copy operation, we copy the
443 * SYSTEM_BUILD_INFOS_FILE to the BUILD_INFOS_FILE.
444 * We then just have to load both and compare them -- if they
445 * are different the current system is newer.
446 *
447 * Loading and comparing the strings should be faster than
448 * creating a hash, the files being rather small. Extracting the
449 * version number would require some parsing which may be more
450 * brittle.
451 */
452 public boolean newSystemImage() {
453 try {
454 File buildInfoFile = new File(SYSTEM_BUILD_INFOS_FILE);
455 File buildInfoPlugins = new File(pluginsPath, BUILD_INFOS_FILE);
456 if (!buildInfoPlugins.exists()) {
457 if (Config.LOGV) {
458 Log.v(TAG, "build.prop in plugins directory " + pluginsPath
459 + " does not exist, therefore it's a new system image");
460 }
461 return true;
462 } else {
463 String buildInfo = contentsOfFile(buildInfoFile);
464 String buildInfoPlugin = contentsOfFile(buildInfoPlugins);
465 if (buildInfo == null || buildInfoPlugin == null
466 || buildInfo.compareTo(buildInfoPlugin) != 0) {
467 if (Config.LOGV) {
468 Log.v(TAG, "build.prop are different, "
469 + " therefore it's a new system image");
470 }
471 return true;
472 }
473 }
474 } catch (Exception e) {
475 Log.e(TAG, "Exc in newSystemImage(): " + e);
476 }
477 return false;
478 }
479
480 /**
481 * Check if the version of the plugins contained in the
482 * Browser assets is the same as the version of the plugins
483 * in the plugins directory.
484 * We simply iterate on every file in the assets/plugins
485 * and return false if a file listed in the assets does
486 * not exist in the plugins directory.
487 */
488 private boolean checkIsDifferentVersions() {
489 try {
490 ZipFile zip = new ZipFile(APK_PATH);
491 Vector<ZipEntry> files = pluginsFilesFromZip(zip);
492 int zipFilterLength = ZIP_FILTER.length();
493
494 Enumeration entries = files.elements();
495 while (entries.hasMoreElements()) {
496 ZipEntry entry = (ZipEntry) entries.nextElement();
497 String path = entry.getName().substring(zipFilterLength);
498 File outputFile = new File(pluginsPath, path);
499 if (!outputFile.exists()) {
500 if (Config.LOGV) {
501 Log.v(TAG, "checkIsDifferentVersions(): extracted file "
502 + path + " does not exist, we have a different version");
503 }
504 return true;
505 }
506 }
507 } catch (IOException e) {
508 Log.e(TAG, "Exception in checkDifferentVersions(): " + e);
509 }
510 return false;
511 }
512
513 /**
514 * Copy every files from the assets/plugins directory
515 * to the app_plugins directory in the data partition.
516 * Once copied, we copy over the SYSTEM_BUILD_INFOS file
517 * in the plugins directory.
518 *
519 * NOTE: we directly access the content from the Browser
520 * package (it's a zip file) and do not use AssetManager
521 * as there is a limit of 1Mb (see Asset.h)
522 */
523 public void run() {
The Android Open Source Projected217d92008-12-17 18:05:52 -0800524 // Lower the priority
525 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700526 try {
527 if (pluginsPath == null) {
528 Log.e(TAG, "No plugins path found!");
529 return;
530 }
531
532 ZipFile zip = new ZipFile(APK_PATH);
533 Vector<ZipEntry> files = pluginsFilesFromZip(zip);
534 Vector<File> plugins = new Vector<File>();
535 int zipFilterLength = ZIP_FILTER.length();
536
537 Enumeration entries = files.elements();
538 while (entries.hasMoreElements()) {
539 ZipEntry entry = (ZipEntry) entries.nextElement();
540 String path = entry.getName().substring(zipFilterLength);
541 File outputFile = new File(pluginsPath, path);
542 outputFile.getParentFile().mkdirs();
543
544 if (outputFile.exists() && !mDoOverwrite) {
545 if (Config.LOGV) {
546 Log.v(TAG, path + " already extracted.");
547 }
548 } else {
549 if (path.endsWith(PLUGIN_EXTENSION)) {
550 // We rename plugins to be sure a half-copied
551 // plugin is not loaded by the browser.
552 plugins.add(outputFile);
553 outputFile = new File(pluginsPath,
554 path + TEMPORARY_EXTENSION);
555 }
556 FileOutputStream fos = new FileOutputStream(outputFile);
557 if (Config.LOGV) {
558 Log.v(TAG, "copy " + entry + " to "
559 + pluginsPath + "/" + path);
560 }
561 copyStreams(zip.getInputStream(entry), fos);
562 }
563 }
564
565 // We now rename the .so we copied, once all their resources
566 // are safely copied over to the user data partition.
567 Enumeration elems = plugins.elements();
568 while (elems.hasMoreElements()) {
569 File renamedFile = (File) elems.nextElement();
570 File sourceFile = new File(renamedFile.getPath()
571 + TEMPORARY_EXTENSION);
572 if (Config.LOGV) {
573 Log.v(TAG, "rename " + sourceFile.getPath()
574 + " to " + renamedFile.getPath());
575 }
576 sourceFile.renameTo(renamedFile);
577 }
578
579 copyBuildInfos();
580
581 // Refresh the plugin list.
582 if (mWebView != null)
583 mWebView.refreshPlugins(false);
584 } catch (IOException e) {
585 Log.e(TAG, "IO Exception: " + e);
586 }
587 }
588 };
589
590 /**
591 * Copy the content of assets/plugins/ to the app_plugins directory
592 * in the data partition.
593 *
594 * This function is called every time the browser is started.
595 * We first check if the system image is newer than the one that
596 * copied the plugins (if there's plugins in the data partition).
597 * If this is the case, we then check if the versions are different.
598 * If they are different, we clean the plugins directory in the
599 * data partition, then start a thread to copy the plugins while
600 * the browser continue to load.
601 *
602 * @param overwrite if true overwrite the files even if they are
603 * already present (to let the user "reset" the plugins if needed).
604 */
605 private void copyPlugins(boolean overwrite) {
606 CopyPlugins copyPluginsFromAssets = new CopyPlugins(overwrite, this);
607 copyPluginsFromAssets.initPluginsPath();
608 if (copyPluginsFromAssets.newSystemImage()) {
609 if (copyPluginsFromAssets.checkIsDifferentVersions()) {
610 copyPluginsFromAssets.cleanPluginsDirectory();
The Android Open Source Projected217d92008-12-17 18:05:52 -0800611 Thread copyplugins = new Thread(copyPluginsFromAssets);
612 copyplugins.setName("CopyPlugins");
613 copyplugins.start();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700614 }
615 }
616 }
617
The Android Open Source Projected217d92008-12-17 18:05:52 -0800618 private class ClearThumbnails extends AsyncTask<File, Void, Void> {
619 @Override
620 public Void doInBackground(File... files) {
621 if (files != null) {
622 for (File f : files) {
623 f.delete();
624 }
625 }
626 return null;
627 }
628 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700629
630 @Override public void onCreate(Bundle icicle) {
631 if (Config.LOGV) {
632 Log.v(LOGTAG, this + " onStart");
633 }
634 super.onCreate(icicle);
635 this.requestWindowFeature(Window.FEATURE_LEFT_ICON);
636 this.requestWindowFeature(Window.FEATURE_RIGHT_ICON);
637 this.requestWindowFeature(Window.FEATURE_PROGRESS);
638 this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
639
640 // test the browser in OpenGL
641 // requestWindowFeature(Window.FEATURE_OPENGL);
642
643 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
644
645 mResolver = getContentResolver();
646
The Android Open Source Projected217d92008-12-17 18:05:52 -0800647 setBaseSearchUrl(PreferenceManager.getDefaultSharedPreferences(this)
648 .getString("search_url", ""));
649
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700650 //
651 // start MASF proxy service
652 //
653 //Intent proxyServiceIntent = new Intent();
654 //proxyServiceIntent.setComponent
655 // (new ComponentName(
656 // "com.android.masfproxyservice",
657 // "com.android.masfproxyservice.MasfProxyService"));
658 //startService(proxyServiceIntent, null);
659
660 mSecLockIcon = Resources.getSystem().getDrawable(
661 android.R.drawable.ic_secure);
662 mMixLockIcon = Resources.getSystem().getDrawable(
663 android.R.drawable.ic_partial_secure);
664 mGenericFavicon = getResources().getDrawable(
665 R.drawable.app_web_browser_sm);
666
667
668 mContentView = new FrameLayout(this);
669
670 setContentView(mContentView);
671
672 // Create the tab control and our initial tab
673 mTabControl = new TabControl(this);
674
675 // Open the icon database and retain all the bookmark urls for favicons
676 retainIconsOnStartup();
677
678 // Keep a settings instance handy.
679 mSettings = BrowserSettings.getInstance();
680 mSettings.setTabControl(mTabControl);
681 mSettings.loadFromDb(this);
682
683 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
684 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
685
686 if (!mTabControl.restoreState(icicle)) {
The Android Open Source Projected217d92008-12-17 18:05:52 -0800687 // clear up the thumbnail directory if we can't restore the state as
688 // none of the files in the directory are referenced any more.
689 new ClearThumbnails().execute(
690 mTabControl.getThumbnailDir().listFiles());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700691 final Intent intent = getIntent();
692 final Bundle extra = intent.getExtras();
693 // Create an initial tab.
The Android Open Source Projected217d92008-12-17 18:05:52 -0800694 // If the intent is ACTION_VIEW and data is not null, the Browser is
695 // invoked to view the content by another application. In this case,
696 // the tab will be close when exit.
697 final TabControl.Tab t = mTabControl.createNewTab(
698 Intent.ACTION_VIEW.equals(intent.getAction()) &&
699 intent.getData() != null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700700 mTabControl.setCurrentTab(t);
701 // This is one of the only places we call attachTabToContentView
702 // without animating from the tab picker.
703 attachTabToContentView(t);
704 mWebView = t.getWebView();
705 if (extra != null) {
706 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
707 if (scale > 0 && scale <= 1000) {
708 mWebView.setInitialScale(scale);
709 }
710 }
711 // If we are not restoring from an icicle, then there is a high
712 // likely hood this is the first run. So, check to see if the
713 // homepage needs to be configured and copy any plugins from our
714 // asset directory to the data partition.
715 if ((extra == null || !extra.getBoolean("testing"))
716 && !mSettings.isLoginInitialized()) {
717 setupHomePage();
718 }
719 copyPlugins(true);
720
721 String url = getUrlFromIntent(intent);
722 if (url == null || url.length() == 0) {
723 if (mSettings.isLoginInitialized()) {
724 mWebView.loadUrl(mSettings.getHomePage());
725 } else {
726 waitForCredentials();
727 }
728 } else {
729 mWebView.loadUrl(url);
730 }
731 } else {
732 // TabControl.restoreState() will create a new tab even if
733 // restoring the state fails. Attach it to the view here since we
734 // are not animating from the tab picker.
735 attachTabToContentView(mTabControl.getCurrentTab());
736 mWebView = mTabControl.getCurrentWebView();
737 }
738
739 /* enables registration for changes in network status from
740 http stack */
741 mNetworkStateChangedFilter = new IntentFilter();
742 mNetworkStateChangedFilter.addAction(
743 RequestQueue.HTTP_NETWORK_STATE_CHANGED_INTENT);
744 mNetworkStateIntentReceiver = new BroadcastReceiver() {
745 @Override
746 public void onReceive(Context context, Intent intent) {
747 if (intent.getAction().equals(
748 RequestQueue.HTTP_NETWORK_STATE_CHANGED_INTENT)) {
749 Boolean up = (Boolean)intent.getExtra(
750 RequestQueue.HTTP_NETWORK_STATE_UP);
751 onNetworkToggle(up);
752 }
753 }
754 };
755 setRequestedOrientation(mSettings.getOrientation());
756 }
757
758 @Override
759 protected void onNewIntent(Intent intent) {
The Android Open Source Projected217d92008-12-17 18:05:52 -0800760 // When a tab is closed on exit, the current tab index is set to -1.
761 // Reset before proceed as Browser requires the current tab to be set.
762 if (mTabControl.getCurrentIndex() == -1) {
763 TabControl.Tab current = mTabControl.getTab(0);
764 mTabControl.setCurrentTab(current);
765 attachTabToContentView(current);
766 mWebView = current.getWebView();
767 resetTitleAndIcon(mWebView);
768 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700769 if (mWebView == null) {
770 return;
771 }
772 final String action = intent.getAction();
773 final int flags = intent.getFlags();
774 if (Intent.ACTION_MAIN.equals(action) ||
775 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
776 // just resume the browser
777 return;
778 }
779 if (Intent.ACTION_VIEW.equals(action)
780 || Intent.ACTION_SEARCH.equals(action)
The Android Open Source Projected217d92008-12-17 18:05:52 -0800781 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700782 || Intent.ACTION_WEB_SEARCH.equals(action)) {
783 String url = getUrlFromIntent(intent);
784 if (url == null || url.length() == 0) {
785 url = mSettings.getHomePage();
786 }
787 if (Intent.ACTION_VIEW.equals(action) &&
788 (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
789 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url will be
The Android Open Source Projected217d92008-12-17 18:05:52 -0800790 // opened in a new tab unless we have reached MAX_TABS. Then the
791 // url will be opened in the current tab. If a new tab is
792 // created, it will have "true" for exit on close.
793 openTabAndShow(url, null, true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700794 } else {
795 if ("about:debug".equals(url)) {
796 mSettings.toggleDebugSettings();
797 return;
798 }
799 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
800 // If the Window overview is up and we are not in the midst of
801 // an animation, animate away from the Window overview.
802 if (mTabOverview != null && mAnimationCount == 0) {
803 sendAnimateFromOverview(currentTab, false, url,
804 TAB_OVERVIEW_DELAY, null);
805 } else {
806 // Get rid of the subwindow if it exists
807 dismissSubWindow(currentTab);
808 mWebView.loadUrl(url);
809 }
810 }
811 }
812 }
813
814 private String getUrlFromIntent(Intent intent) {
815 String url = null;
816 if (intent != null) {
817 final String action = intent.getAction();
818 if (Intent.ACTION_VIEW.equals(action)) {
819 url = smartUrlFilter(intent.getData());
820 if (url != null && url.startsWith("content:")) {
821 /* Append mimetype so webview knows how to display */
822 String mimeType = intent.resolveType(getContentResolver());
823 if (mimeType != null) {
824 url += "?" + mimeType;
825 }
826 }
827 } else if (Intent.ACTION_SEARCH.equals(action)
The Android Open Source Projected217d92008-12-17 18:05:52 -0800828 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700829 || Intent.ACTION_WEB_SEARCH.equals(action)) {
830 url = intent.getStringExtra(SearchManager.QUERY);
The Android Open Source Projected217d92008-12-17 18:05:52 -0800831 if (url != null) {
832 mLastEnteredUrl = url;
833 // Don't add Urls, just search terms.
834 // Urls will get added when the page is loaded.
835 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
836 Browser.updateVisitedHistory(mResolver, url, false);
837 }
838 // In general, we shouldn't modify URL from Intent.
839 // But currently, we get the user-typed URL from search box as well.
840 url = fixUrl(url);
841 url = smartUrlFilter(url);
842 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
843 if (url.contains(searchSource)) {
844 String source = null;
845 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
846 if (appData != null) {
847 source = appData.getString(SearchManager.SOURCE);
848 }
849 if (TextUtils.isEmpty(source)) {
850 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
851 }
852 url = url.replace(searchSource, "&source=android-"+source+"&");
853 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700854 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700855 }
856 }
857 return url;
858 }
859
The Android Open Source Projected217d92008-12-17 18:05:52 -0800860 /* package */ static String fixUrl(String inUrl) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700861 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
862 return inUrl;
863 if (inUrl.startsWith("http:") ||
864 inUrl.startsWith("https:")) {
865 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
866 inUrl = inUrl.replaceFirst("/", "//");
867 } else inUrl = inUrl.replaceFirst(":", "://");
868 }
869 return inUrl;
870 }
871
872 /**
873 * Looking for the pattern like this
874 *
875 * *
876 * * *
877 * *** * *******
878 * * *
879 * * *
880 * *
881 */
882 private final SensorListener mSensorListener = new SensorListener() {
883 private long mLastGestureTime;
884 private float[] mPrev = new float[3];
885 private float[] mPrevDiff = new float[3];
886 private float[] mDiff = new float[3];
887 private float[] mRevertDiff = new float[3];
888
889 public void onSensorChanged(int sensor, float[] values) {
890 boolean show = false;
891 float[] diff = new float[3];
892
893 for (int i = 0; i < 3; i++) {
894 diff[i] = values[i] - mPrev[i];
895 if (Math.abs(diff[i]) > 1) {
896 show = true;
897 }
898 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
899 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
900 // start track when there is a big move, or revert
901 mRevertDiff[i] = mDiff[i];
902 mDiff[i] = 0;
903 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
904 // reset when it is flat
905 mDiff[i] = mRevertDiff[i] = 0;
906 }
907 mDiff[i] += diff[i];
908 mPrevDiff[i] = diff[i];
909 mPrev[i] = values[i];
910 }
911
912 if (false) {
913 // only shows if we think the delta is big enough, in an attempt
914 // to detect "serious" moves left/right or up/down
915 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
916 + values[0] + ", " + values[1] + ", " + values[2] + ")"
917 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
918 + ")");
919 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
920 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
921 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
922 + mRevertDiff[2] + ")");
923 }
924
925 long now = android.os.SystemClock.uptimeMillis();
926 if (now - mLastGestureTime > 1000) {
927 mLastGestureTime = 0;
928
929 float y = mDiff[1];
930 float z = mDiff[2];
931 float ay = Math.abs(y);
932 float az = Math.abs(z);
933 float ry = mRevertDiff[1];
934 float rz = mRevertDiff[2];
935 float ary = Math.abs(ry);
936 float arz = Math.abs(rz);
937 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
938 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
939
940 if ((gestY || gestZ) && !(gestY && gestZ)) {
941 WebView view = mWebView;
942
943 if (gestZ) {
944 if (z < 0) {
945 view.zoomOut();
946 } else {
947 view.zoomIn();
948 }
949 } else {
950 view.flingScroll(0, Math.round(y * 100));
951 }
952 mLastGestureTime = now;
953 }
954 }
955 }
956
957 public void onAccuracyChanged(int sensor, int accuracy) {
958 // TODO Auto-generated method stub
959
960 }
961 };
962
963 @Override protected void onResume() {
964 super.onResume();
965 if (Config.LOGV) {
966 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
967 }
968
969 if (!mActivityInPause) {
970 Log.e(LOGTAG, "BrowserActivity is already resumed.");
971 return;
972 }
973
974 mActivityInPause = false;
975 resumeWebView();
976
977 if (mWakeLock.isHeld()) {
978 mHandler.removeMessages(RELEASE_WAKELOCK);
979 mWakeLock.release();
980 }
981
982 if (mCredsDlg != null) {
983 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
984 // In case credential request never comes back
985 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
986 }
987 }
988
989 registerReceiver(mNetworkStateIntentReceiver,
990 mNetworkStateChangedFilter);
991 WebView.enablePlatformNotifications();
992
993 if (mSettings.doFlick()) {
994 if (mSensorManager == null) {
995 mSensorManager = (SensorManager) getSystemService(
996 Context.SENSOR_SERVICE);
997 }
998 mSensorManager.registerListener(mSensorListener,
999 SensorManager.SENSOR_ACCELEROMETER,
1000 SensorManager.SENSOR_DELAY_FASTEST);
1001 } else {
1002 mSensorManager = null;
1003 }
1004 }
1005
1006 /**
1007 * onSaveInstanceState(Bundle map)
1008 * onSaveInstanceState is called right before onStop(). The map contains
1009 * the saved state.
1010 */
1011 @Override protected void onSaveInstanceState(Bundle outState) {
1012 if (Config.LOGV) {
1013 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1014 }
1015 // the default implementation requires each view to have an id. As the
1016 // browser handles the state itself and it doesn't use id for the views,
1017 // don't call the default implementation. Otherwise it will trigger the
1018 // warning like this, "couldn't save which view has focus because the
1019 // focused view XXX has no id".
1020
1021 // Save all the tabs
1022 mTabControl.saveState(outState);
1023 }
1024
1025 @Override protected void onPause() {
1026 super.onPause();
1027
1028 if (mActivityInPause) {
1029 Log.e(LOGTAG, "BrowserActivity is already paused.");
1030 return;
1031 }
1032
1033 mActivityInPause = true;
The Android Open Source Projected217d92008-12-17 18:05:52 -08001034 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebView()) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001035 mWakeLock.acquire();
1036 mHandler.sendMessageDelayed(mHandler
1037 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1038 }
1039
1040 // Clear the credentials toast if it is up
1041 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1042 mCredsDlg.dismiss();
1043 }
1044 mCredsDlg = null;
1045
1046 cancelStopToast();
1047
1048 // unregister network state listener
1049 unregisterReceiver(mNetworkStateIntentReceiver);
1050 WebView.disablePlatformNotifications();
1051
1052 if (mSensorManager != null) {
1053 mSensorManager.unregisterListener(mSensorListener);
1054 }
1055 }
1056
1057 @Override protected void onDestroy() {
1058 if (Config.LOGV) {
1059 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1060 }
1061 super.onDestroy();
1062 // Remove the current tab and sub window
1063 TabControl.Tab t = mTabControl.getCurrentTab();
1064 dismissSubWindow(t);
1065 removeTabFromContentView(t);
1066 // Destroy all the tabs
1067 mTabControl.destroy();
1068 WebIconDatabase.getInstance().close();
1069 if (mGlsConnection != null) {
1070 unbindService(mGlsConnection);
1071 mGlsConnection = null;
1072 }
1073
1074 //
1075 // stop MASF proxy service
1076 //
1077 //Intent proxyServiceIntent = new Intent();
1078 //proxyServiceIntent.setComponent
1079 // (new ComponentName(
1080 // "com.android.masfproxyservice",
1081 // "com.android.masfproxyservice.MasfProxyService"));
1082 //stopService(proxyServiceIntent);
1083 }
1084
1085 @Override
1086 public void onConfigurationChanged(Configuration newConfig) {
1087 super.onConfigurationChanged(newConfig);
1088
1089 if (mPageInfoDialog != null) {
1090 mPageInfoDialog.dismiss();
1091 showPageInfo(
1092 mPageInfoView,
1093 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1094 }
1095 if (mSSLCertificateDialog != null) {
1096 mSSLCertificateDialog.dismiss();
1097 showSSLCertificate(
1098 mSSLCertificateView);
1099 }
1100 if (mSSLCertificateOnErrorDialog != null) {
1101 mSSLCertificateOnErrorDialog.dismiss();
1102 showSSLCertificateOnError(
1103 mSSLCertificateOnErrorView,
1104 mSSLCertificateOnErrorHandler,
1105 mSSLCertificateOnErrorError);
1106 }
1107 if (mHttpAuthenticationDialog != null) {
1108 String title = ((TextView) mHttpAuthenticationDialog
1109 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1110 .toString();
1111 String name = ((TextView) mHttpAuthenticationDialog
1112 .findViewById(R.id.username_edit)).getText().toString();
1113 String password = ((TextView) mHttpAuthenticationDialog
1114 .findViewById(R.id.password_edit)).getText().toString();
1115 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1116 .getId();
1117 mHttpAuthenticationDialog.dismiss();
1118 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1119 name, password, focusId);
1120 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08001121 if (mFindDialog != null && mFindDialog.isShowing()) {
1122 mFindDialog.onConfigurationChanged(newConfig);
1123 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001124 }
1125
1126 @Override public void onLowMemory() {
1127 super.onLowMemory();
1128 mTabControl.freeMemory();
1129 }
1130
1131 private boolean resumeWebView() {
1132 if ((!mActivityInPause && !mPageStarted) ||
1133 (mActivityInPause && mPageStarted)) {
1134 CookieSyncManager.getInstance().startSync();
1135 mWebView.resumeTimers();
1136 return true;
1137 } else {
1138 return false;
1139 }
1140 }
1141
1142 private boolean pauseWebView() {
1143 if (mActivityInPause && !mPageStarted) {
1144 CookieSyncManager.getInstance().stopSync();
1145 mWebView.pauseTimers();
1146 return true;
1147 } else {
1148 return false;
1149 }
1150 }
1151
1152 /*
1153 * This function is called when we are launching for the first time. We
1154 * are waiting for the login credentials before loading Google home
1155 * pages. This way the user will be logged in straight away.
1156 */
1157 private void waitForCredentials() {
1158 // Show a toast
1159 mCredsDlg = new ProgressDialog(this);
1160 mCredsDlg.setIndeterminate(true);
1161 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1162 // If the user cancels the operation, then cancel the Google
1163 // Credentials request.
1164 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1165 mCredsDlg.show();
1166
1167 // We set a timeout for the retrieval of credentials in onResume()
1168 // as that is when we have freed up some CPU time to get
1169 // the login credentials.
1170 }
1171
1172 /*
1173 * If we have received the credentials or we have timed out and we are
1174 * showing the credentials dialog, then it is time to move on.
1175 */
1176 private void resumeAfterCredentials() {
1177 if (mCredsDlg == null) {
1178 return;
1179 }
1180
1181 // Clear the toast
1182 if (mCredsDlg.isShowing()) {
1183 mCredsDlg.dismiss();
1184 }
1185 mCredsDlg = null;
1186
1187 // Clear any pending timeout
1188 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1189
1190 // Load the page
1191 mWebView.loadUrl(mSettings.getHomePage());
1192
1193 // Update the settings, need to do this last as it can take a moment
1194 // to persist the settings. In the mean time we could be loading
1195 // content.
1196 mSettings.setLoginInitialized(this);
1197 }
1198
1199 // Open the icon database and retain all the icons for visited sites.
1200 private void retainIconsOnStartup() {
1201 final WebIconDatabase db = WebIconDatabase.getInstance();
1202 db.open(getDir("icons", 0).getPath());
1203 try {
1204 Cursor c = Browser.getAllBookmarks(mResolver);
1205 if (!c.moveToFirst()) {
1206 c.deactivate();
1207 return;
1208 }
1209 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1210 do {
1211 String url = c.getString(urlIndex);
1212 db.retainIconForPageUrl(url);
1213 } while (c.moveToNext());
1214 c.deactivate();
1215 } catch (IllegalStateException e) {
1216 Log.e(LOGTAG, "retainIconsOnStartup", e);
1217 }
1218 }
1219
1220 // Helper method for getting the top window.
1221 WebView getTopWindow() {
1222 return mTabControl.getCurrentTopWebView();
1223 }
1224
1225 @Override
1226 public boolean onCreateOptionsMenu(Menu menu) {
1227 super.onCreateOptionsMenu(menu);
1228
1229 MenuInflater inflater = getMenuInflater();
1230 inflater.inflate(R.menu.browser, menu);
1231 mMenu = menu;
1232 updateInLoadMenuItems();
1233 return true;
1234 }
1235
1236 /**
1237 * As the menu can be open when loading state changes
1238 * we must manually update the state of the stop/reload menu
1239 * item
1240 */
1241 private void updateInLoadMenuItems() {
1242 if (mMenu == null) {
1243 return;
1244 }
1245 MenuItem src = mInLoad ?
1246 mMenu.findItem(R.id.stop_menu_id):
1247 mMenu.findItem(R.id.reload_menu_id);
1248 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1249 dest.setIcon(src.getIcon());
1250 dest.setTitle(src.getTitle());
1251 }
1252
1253 @Override
1254 public boolean onContextItemSelected(MenuItem item) {
1255 // chording is not an issue with context menus, but we use the same
1256 // options selector, so set mCanChord to true so we can access them.
1257 mCanChord = true;
1258 int id = item.getItemId();
The Android Open Source Projected217d92008-12-17 18:05:52 -08001259 final WebView webView = getTopWindow();
1260 final HashMap hrefMap = new HashMap();
1261 hrefMap.put("webview", webView);
1262 final Message msg = mHandler.obtainMessage(
1263 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001264 switch (id) {
1265 // -- Browser context menu
1266 case R.id.open_context_menu_id:
1267 case R.id.open_newtab_context_menu_id:
1268 case R.id.bookmark_context_menu_id:
1269 case R.id.save_link_context_menu_id:
1270 case R.id.share_link_context_menu_id:
1271 case R.id.copy_link_context_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001272 webView.requestFocusNodeHref(msg);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001273 break;
1274
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001275 default:
1276 // For other context menus
1277 return onOptionsItemSelected(item);
1278 }
1279 mCanChord = false;
1280 return true;
1281 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08001282
1283 private Bundle createGoogleSearchSourceBundle(String source) {
1284 Bundle bundle = new Bundle();
1285 bundle.putString(SearchManager.SOURCE, source);
1286 return bundle;
1287 }
1288
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001289 /**
1290 * Overriding this forces the search key to launch global search. The difference
1291 * is the final "true" which requests global search.
1292 */
1293 @Override
1294 public boolean onSearchRequested() {
The Android Open Source Projected217d92008-12-17 18:05:52 -08001295 startSearch(null, false,
1296 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001297 return true;
1298 }
1299
1300 @Override
The Android Open Source Projected217d92008-12-17 18:05:52 -08001301 public void startSearch(String initialQuery, boolean selectInitialQuery,
1302 Bundle appSearchData, boolean globalSearch) {
1303 if (appSearchData == null) {
1304 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1305 }
1306 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1307 }
1308
1309 @Override
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001310 public boolean onOptionsItemSelected(MenuItem item) {
1311 if (!mCanChord) {
1312 // The user has already fired a shortcut with this hold down of the
1313 // menu key.
1314 return false;
1315 }
1316 switch (item.getItemId()) {
1317 // -- Main menu
1318 case R.id.goto_menu_id: {
1319 String url = getTopWindow().getUrl();
The Android Open Source Projected217d92008-12-17 18:05:52 -08001320 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1321 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_GOTO), false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001322 }
1323 break;
The Android Open Source Projected217d92008-12-17 18:05:52 -08001324
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001325 case R.id.search_menu_id:
1326 // launch using "global" search, which will bring up the Google search box
The Android Open Source Projected217d92008-12-17 18:05:52 -08001327 startSearch(null, false,
1328 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHMENU), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001329 break;
The Android Open Source Projected217d92008-12-17 18:05:52 -08001330
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001331 case R.id.bookmarks_menu_id:
1332 bookmarksPicker();
1333 break;
1334
1335 case R.id.windows_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001336 if (mTabControl.getTabCount() == 1) {
1337 openTabAndShow(mSettings.getHomePage(), null, false);
1338 } else {
1339 tabPicker(true, mTabControl.getCurrentIndex(), false);
1340 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001341 break;
1342
1343 case R.id.stop_reload_menu_id:
1344 if (mInLoad) {
1345 stopLoading();
1346 } else {
1347 getTopWindow().reload();
1348 }
1349 break;
1350
1351 case R.id.back_menu_id:
1352 getTopWindow().goBack();
1353 break;
1354
1355 case R.id.forward_menu_id:
1356 getTopWindow().goForward();
1357 break;
1358
1359 case R.id.close_menu_id:
1360 // Close the subwindow if it exists.
1361 if (mTabControl.getCurrentSubWindow() != null) {
1362 dismissSubWindow(mTabControl.getCurrentTab());
1363 break;
1364 }
1365 final int currentIndex = mTabControl.getCurrentIndex();
1366 final TabControl.Tab parent =
1367 mTabControl.getCurrentTab().getParentTab();
1368 int indexToShow = -1;
1369 if (parent != null) {
1370 indexToShow = mTabControl.getTabIndex(parent);
1371 } else {
1372 // Get the last tab in the list. If it is the current tab,
1373 // subtract 1 more.
1374 indexToShow = mTabControl.getTabCount() - 1;
1375 if (currentIndex == indexToShow) {
1376 indexToShow--;
1377 }
1378 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08001379 switchTabs(currentIndex, indexToShow, true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001380 break;
1381
1382 case R.id.homepage_menu_id:
1383 dismissSubWindow(mTabControl.getCurrentTab());
1384 mWebView.loadUrl(mSettings.getHomePage());
1385 break;
1386
1387 case R.id.preferences_menu_id:
1388 Intent intent = new Intent(this,
1389 BrowserPreferencesPage.class);
1390 startActivityForResult(intent, PREFERENCES_PAGE);
1391 break;
1392
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001393 case R.id.find_menu_id:
1394 if (null == mFindDialog) {
1395 mFindDialog = new FindDialog(this);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001396 }
1397 mFindDialog.setWebView(getTopWindow());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001398 mFindDialog.show();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001399 mMenuState = EMPTY_MENU;
1400 break;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001401
1402 case R.id.page_info_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001403 showPageInfo(mTabControl.getCurrentTab(), false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001404 break;
1405
The Android Open Source Projected217d92008-12-17 18:05:52 -08001406 case R.id.classic_history_menu_id:
1407 loadHistory();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001408 break;
1409
1410 case R.id.bookmark_page_menu_id:
1411 Browser.saveBookmark(this, getTopWindow().getTitle(),
1412 getTopWindow().getUrl());
1413 break;
1414
1415 case R.id.share_page_menu_id:
1416 Browser.sendString(this, getTopWindow().getUrl());
1417 break;
1418
1419 case R.id.dump_nav_menu_id:
1420 getTopWindow().debugDump();
1421 break;
1422
1423 case R.id.zoom_menu_id:
1424 // FIXME: Can we move this out of WebView? How does this work
1425 // for a subwindow?
1426 getTopWindow().invokeZoomPicker();
1427 break;
1428
1429 case R.id.zoom_in_menu_id:
1430 getTopWindow().zoomIn();
1431 break;
1432
1433 case R.id.zoom_out_menu_id:
1434 getTopWindow().zoomOut();
1435 break;
1436
1437 case R.id.view_downloads_menu_id:
1438 viewDownloads(null);
1439 break;
1440
1441 case R.id.flip_orientation_menu_id:
1442 if (mSettings.getOrientation() !=
1443 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
1444 mSettings.setOrientation(this,
1445 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
1446 } else {
1447 mSettings.setOrientation(this,
1448 ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
1449 }
1450 setRequestedOrientation(mSettings.getOrientation());
1451 break;
1452
1453 // -- Tab menu
1454 case R.id.view_tab_menu_id:
1455 if (mTabListener != null && mTabOverview != null) {
1456 int pos = mTabOverview.getContextMenuPosition(item);
1457 mTabOverview.setCurrentIndex(pos);
1458 mTabListener.onClick(pos);
1459 }
1460 break;
1461
1462 case R.id.remove_tab_menu_id:
1463 if (mTabListener != null && mTabOverview != null) {
1464 int pos = mTabOverview.getContextMenuPosition(item);
1465 mTabListener.remove(pos);
1466 }
1467 break;
1468
1469 case R.id.new_tab_menu_id:
1470 // No need to check for mTabOverview here since we are not
1471 // dependent on it for a position.
1472 if (mTabListener != null) {
1473 // If the overview happens to be non-null, make the "New
1474 // Tab" cell visible.
1475 if (mTabOverview != null) {
1476 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1477 }
1478 mTabListener.onClick(ImageGrid.NEW_TAB);
1479 }
1480 break;
1481
1482 case R.id.bookmark_tab_menu_id:
1483 if (mTabListener != null && mTabOverview != null) {
1484 int pos = mTabOverview.getContextMenuPosition(item);
1485 TabControl.Tab t = mTabControl.getTab(pos);
1486 // Since we called populatePickerData for all of the
1487 // tabs, getTitle and getUrl will return appropriate
1488 // values.
1489 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1490 t.getUrl());
1491 }
1492 break;
1493
1494 case R.id.history_tab_menu_id: {
1495 Intent i = new Intent(this, BrowserHistoryPage.class);
1496 i.putExtra("maxTabsOpen",
1497 mTabControl.getTabCount() >=
1498 TabControl.MAX_TABS);
1499 startActivityForResult(i, CLASSIC_HISTORY_PAGE);
1500 }
1501 break;
1502
1503 case R.id.bookmarks_tab_menu_id:
1504 bookmarksPicker();
1505 break;
1506
1507 case R.id.properties_tab_menu_id:
1508 if (mTabListener != null && mTabOverview != null) {
1509 int pos = mTabOverview.getContextMenuPosition(item);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001510 showPageInfo(mTabControl.getTab(pos), false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001511 }
1512 break;
1513
The Android Open Source Projected217d92008-12-17 18:05:52 -08001514 case R.id.window_one_menu_id:
1515 case R.id.window_two_menu_id:
1516 case R.id.window_three_menu_id:
1517 case R.id.window_four_menu_id:
1518 case R.id.window_five_menu_id:
1519 case R.id.window_six_menu_id:
1520 case R.id.window_seven_menu_id:
1521 case R.id.window_eight_menu_id:
1522 {
1523 int menuid = item.getItemId();
1524 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1525 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1526 TabControl.Tab desiredTab = mTabControl.getTab(id);
1527 if (desiredTab != null &&
1528 desiredTab != mTabControl.getCurrentTab()) {
1529 switchTabs(mTabControl.getCurrentIndex(), id, false);
1530 }
1531 break;
1532 }
1533 }
1534 }
1535 break;
1536
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001537 default:
1538 if (!super.onOptionsItemSelected(item)) {
1539 return false;
1540 }
1541 // Otherwise fall through.
1542 }
1543 mCanChord = false;
1544 return true;
1545 }
1546
1547 public void closeFind() {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001548 mMenuState = R.id.MAIN_MENU;
1549 }
1550
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001551 @Override public boolean onPrepareOptionsMenu(Menu menu)
1552 {
1553 // This happens when the user begins to hold down the menu key, so
1554 // allow them to chord to get a shortcut.
1555 mCanChord = true;
1556 // Note: setVisible will decide whether an item is visible; while
1557 // setEnabled() will decide whether an item is enabled, which also means
1558 // whether the matching shortcut key will function.
1559 super.onPrepareOptionsMenu(menu);
1560 switch (mMenuState) {
1561 case R.id.TAB_MENU:
1562 if (mCurrentMenuState != mMenuState) {
1563 menu.setGroupVisible(R.id.MAIN_MENU, false);
1564 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1565 menu.setGroupVisible(R.id.TAB_MENU, true);
1566 menu.setGroupEnabled(R.id.TAB_MENU, true);
1567 }
1568 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1569 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1570 tab.setVisible(newT);
1571 tab.setEnabled(newT);
1572 break;
1573 case EMPTY_MENU:
1574 if (mCurrentMenuState != mMenuState) {
1575 menu.setGroupVisible(R.id.MAIN_MENU, false);
1576 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1577 menu.setGroupVisible(R.id.TAB_MENU, false);
1578 menu.setGroupEnabled(R.id.TAB_MENU, false);
1579 }
1580 break;
1581 default:
1582 if (mCurrentMenuState != mMenuState) {
1583 menu.setGroupVisible(R.id.MAIN_MENU, true);
1584 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1585 menu.setGroupVisible(R.id.TAB_MENU, false);
1586 menu.setGroupEnabled(R.id.TAB_MENU, false);
1587 }
1588 final WebView w = getTopWindow();
1589 boolean canGoBack = w.canGoBack();
1590 final MenuItem back = menu.findItem(R.id.back_menu_id);
1591 back.setVisible(canGoBack);
1592 back.setEnabled(canGoBack);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001593 final MenuItem flip =
1594 menu.findItem(R.id.flip_orientation_menu_id);
1595 boolean keyboardClosed =
The Android Open Source Projected217d92008-12-17 18:05:52 -08001596 getResources().getConfiguration().hardKeyboardHidden ==
1597 Configuration.HARDKEYBOARDHIDDEN_YES;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001598 flip.setEnabled(keyboardClosed);
1599
1600 boolean isHome = mSettings.getHomePage().equals(w.getUrl());
1601 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1602 home.setVisible(!isHome);
1603 home.setEnabled(!isHome);
1604
1605 menu.findItem(R.id.forward_menu_id)
1606 .setEnabled(w.canGoForward());
1607
1608 menu.findItem(R.id.zoom_in_menu_id).setVisible(false);
1609 menu.findItem(R.id.zoom_out_menu_id).setVisible(false);
1610
1611 // decide whether to show the share link option
1612 PackageManager pm = getPackageManager();
1613 Intent send = new Intent(Intent.ACTION_SEND);
1614 send.setType("text/plain");
1615 List<ResolveInfo> list = pm.queryIntentActivities(send,
1616 PackageManager.MATCH_DEFAULT_ONLY);
1617 menu.findItem(R.id.share_page_menu_id).setVisible(
1618 list.size() > 0);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001619
1620 // Hide the menu+<window number> items
1621 // Can't set visibility in menu xml file b/c when a
1622 // group is set visible, all items are set visible.
1623 for (int i = 0; i < WINDOW_SHORTCUT_ID_ARRAY.length; i++) {
1624 menu.findItem(WINDOW_SHORTCUT_ID_ARRAY[i]).setVisible(false);
1625 }
1626
1627 // If there is only 1 window, the text will be "New window"
1628 final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1629 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1630 getString(R.string.view_tabs_condensed) :
1631 getString(R.string.tab_picker_new_tab));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001632
1633 boolean isNavDump = mSettings.isNavDump();
1634 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1635 nav.setVisible(isNavDump);
1636 nav.setEnabled(isNavDump);
1637 break;
1638 }
1639 mCurrentMenuState = mMenuState;
1640 return true;
1641 }
1642
1643 @Override
1644 public void onCreateContextMenu(ContextMenu menu, View v,
1645 ContextMenuInfo menuInfo) {
1646 WebView webview = (WebView) v;
1647 WebView.HitTestResult result = webview.getHitTestResult();
1648 if (result == null) {
1649 return;
1650 }
1651
1652 int type = result.getType();
1653 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1654 Log.w(LOGTAG,
1655 "We should not show context menu when nothing is touched");
1656 return;
1657 }
1658 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1659 // let TextView handles context menu
1660 return;
1661 }
1662
1663 // Note, http://b/issue?id=1106666 is requesting that
1664 // an inflated menu can be used again. This is not available
1665 // yet, so inflate each time (yuk!)
1666 MenuInflater inflater = getMenuInflater();
1667 inflater.inflate(R.menu.browsercontext, menu);
1668
1669 // Show the correct menu group
1670 String extra = result.getExtra();
1671 menu.setGroupVisible(R.id.PHONE_MENU,
1672 type == WebView.HitTestResult.PHONE_TYPE);
1673 menu.setGroupVisible(R.id.EMAIL_MENU,
1674 type == WebView.HitTestResult.EMAIL_TYPE);
1675 menu.setGroupVisible(R.id.GEO_MENU,
1676 type == WebView.HitTestResult.GEO_TYPE);
1677 menu.setGroupVisible(R.id.IMAGE_MENU,
The Android Open Source Projected217d92008-12-17 18:05:52 -08001678 type == WebView.HitTestResult.IMAGE_TYPE
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001679 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1680 menu.setGroupVisible(R.id.ANCHOR_MENU,
The Android Open Source Projected217d92008-12-17 18:05:52 -08001681 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001682 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1683
1684 // Setup custom handling depending on the type
1685 switch (type) {
1686 case WebView.HitTestResult.PHONE_TYPE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001687 menu.setHeaderTitle(Uri.decode(extra));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001688 menu.findItem(R.id.dial_context_menu_id).setIntent(
1689 new Intent(Intent.ACTION_VIEW, Uri
1690 .parse(WebView.SCHEME_TEL + extra)));
The Android Open Source Projected217d92008-12-17 18:05:52 -08001691 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1692 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1693 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001694 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1695 addIntent);
1696 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1697 new Copy(extra));
1698 break;
1699
1700 case WebView.HitTestResult.EMAIL_TYPE:
1701 menu.setHeaderTitle(extra);
1702 menu.findItem(R.id.email_context_menu_id).setIntent(
1703 new Intent(Intent.ACTION_VIEW, Uri
1704 .parse(WebView.SCHEME_MAILTO + extra)));
1705 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1706 new Copy(extra));
1707 break;
1708
1709 case WebView.HitTestResult.GEO_TYPE:
1710 menu.setHeaderTitle(extra);
1711 menu.findItem(R.id.map_context_menu_id).setIntent(
1712 new Intent(Intent.ACTION_VIEW, Uri
1713 .parse(WebView.SCHEME_GEO
1714 + URLEncoder.encode(extra))));
1715 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1716 new Copy(extra));
1717 break;
1718
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001719 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1720 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001721 TextView titleView = (TextView) LayoutInflater.from(this)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001722 .inflate(android.R.layout.browser_link_context_header,
1723 null);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001724 titleView.setText(extra);
1725 menu.setHeaderView(titleView);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001726 // decide whether to show the open link in new tab option
1727 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1728 mTabControl.getTabCount() < TabControl.MAX_TABS);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001729 PackageManager pm = getPackageManager();
1730 Intent send = new Intent(Intent.ACTION_SEND);
1731 send.setType("text/plain");
1732 List<ResolveInfo> list = pm.queryIntentActivities(send,
1733 PackageManager.MATCH_DEFAULT_ONLY);
1734 menu.findItem(R.id.share_link_context_menu_id).setVisible(
1735 list.size() > 0);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001736 break;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001737
1738 case WebView.HitTestResult.IMAGE_TYPE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001739 menu.setHeaderTitle(extra);
1740 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1741 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1742 menu.findItem(R.id.download_context_menu_id).
1743 setOnMenuItemClickListener(new Download(extra));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001744 break;
1745
1746 default:
1747 Log.w(LOGTAG, "We should not get here.");
1748 break;
1749 }
1750 }
1751
1752 // Used by attachTabToContentView for the WebView's ZoomControl widget.
1753 private static final FrameLayout.LayoutParams ZOOM_PARAMS =
1754 new FrameLayout.LayoutParams(
1755 ViewGroup.LayoutParams.FILL_PARENT,
1756 ViewGroup.LayoutParams.WRAP_CONTENT,
1757 Gravity.BOTTOM);
1758
1759 // Attach the given tab to the content view.
1760 private void attachTabToContentView(TabControl.Tab t) {
1761 final WebView main = t.getWebView();
1762 // Attach the main WebView.
1763 mContentView.addView(main, COVER_SCREEN_PARAMS);
1764 // Attach the Zoom control widget and hide it.
1765 final View zoom = main.getZoomControls();
1766 mContentView.addView(zoom, ZOOM_PARAMS);
1767 zoom.setVisibility(View.GONE);
1768 // Attach the sub window if necessary
1769 attachSubWindow(t);
1770 // Request focus on the top window.
1771 t.getTopWindow().requestFocus();
1772 }
1773
1774 // Attach a sub window to the main WebView of the given tab.
1775 private void attachSubWindow(TabControl.Tab t) {
1776 // If a sub window exists, attach it to the content view.
1777 final WebView subView = t.getSubWebView();
1778 if (subView != null) {
1779 final View container = t.getSubWebViewContainer();
1780 mContentView.addView(container, COVER_SCREEN_PARAMS);
1781 subView.requestFocus();
1782 }
1783 }
1784
1785 // Remove the given tab from the content view.
1786 private void removeTabFromContentView(TabControl.Tab t) {
1787 // Remove the Zoom widget and the main WebView.
1788 mContentView.removeView(t.getWebView().getZoomControls());
1789 mContentView.removeView(t.getWebView());
1790 // Remove the sub window if it exists.
1791 if (t.getSubWebView() != null) {
1792 mContentView.removeView(t.getSubWebViewContainer());
1793 }
1794 }
1795
1796 // Remove the sub window if it exists. Also called by TabControl when the
1797 // user clicks the 'X' to dismiss a sub window.
1798 /* package */ void dismissSubWindow(TabControl.Tab t) {
1799 final WebView mainView = t.getWebView();
1800 if (t.getSubWebView() != null) {
1801 // Remove the container view and request focus on the main WebView.
1802 mContentView.removeView(t.getSubWebViewContainer());
1803 mainView.requestFocus();
1804 // Tell the TabControl to dismiss the subwindow. This will destroy
1805 // the WebView.
1806 mTabControl.dismissSubWindow(t);
1807 }
1808 }
1809
1810 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
1811 private void sendAnimateFromOverview(final TabControl.Tab tab,
1812 final boolean newTab, final String url, final int delay,
1813 final Message msg) {
1814 // Set the current tab.
1815 mTabControl.setCurrentTab(tab);
1816 // Attach the WebView so it will layout.
1817 attachTabToContentView(tab);
1818 // Reset the current WebView.
1819 mWebView = tab.getWebView();
1820 // Set the view to invisibile for now.
1821 mWebView.setVisibility(View.INVISIBLE);
1822 // If there is a sub window, make it invisible too.
1823 if (tab.getSubWebView() != null) {
1824 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
1825 }
1826 // Create our fake animating view.
1827 final AnimatingView view = new AnimatingView(this, tab);
1828 // Attach it to the view system and make in invisible so it will
1829 // layout but not flash white on the screen.
1830 mContentView.addView(view, COVER_SCREEN_PARAMS);
1831 view.setVisibility(View.INVISIBLE);
1832 // Send the animate message.
1833 final HashMap map = new HashMap();
1834 map.put("view", view);
1835 map.put("url", url);
1836 map.put("msg", msg);
1837 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1838 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
1839 // Increment the count to indicate that we are in an animation.
1840 mAnimationCount++;
1841 // Remove the listener so we don't get any more tab changes.
The Android Open Source Projected217d92008-12-17 18:05:52 -08001842 mTabOverview.setListener(null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001843 mTabListener = null;
The Android Open Source Projected217d92008-12-17 18:05:52 -08001844 // Make the menu empty until the animation completes.
1845 mMenuState = EMPTY_MENU;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001846
1847 }
1848
1849 // 500ms animation with 800ms delay
1850 private static final int TAB_ANIMATION_DURATION = 500;
1851 private static final int TAB_OVERVIEW_DELAY = 800;
1852
1853 // Called by TabControl when a tab is requesting focus
1854 /* package */ void showTab(TabControl.Tab t) {
1855 // Disallow focus change during a tab animation.
1856 if (mAnimationCount > 0) {
1857 return;
1858 }
1859 int delay = 0;
1860 if (mTabOverview == null) {
1861 // Add a delay so the tab overview can be shown before the second
1862 // animation begins.
1863 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1864 tabPicker(false, mTabControl.getTabIndex(t), false);
1865 }
1866 sendAnimateFromOverview(t, false, null, delay, null);
1867 }
1868
1869 // This method does a ton of stuff. It will attempt to create a new tab
1870 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1871 // url isn't null, it will load the given url. If the tab overview is not
1872 // showing, it will animate to the tab overview, create a new tab and
1873 // animate away from it. After the animation completes, it will dispatch
1874 // the given Message. If the tab overview is already showing (i.e. this
1875 // method is called from TabListener.onClick(), the method will animate
1876 // away from the tab overview.
The Android Open Source Projected217d92008-12-17 18:05:52 -08001877 private void openTabAndShow(String url, final Message msg,
1878 boolean closeOnExit) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001879 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1880 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1881 if (newTab) {
1882 int delay = 0;
1883 // If the tab overview is up and there are animations, just load
1884 // the url.
1885 if (mTabOverview != null && mAnimationCount > 0) {
1886 if (url != null) {
1887 // We should not have a msg here since onCreateWindow
1888 // checks the animation count and every other caller passes
1889 // null.
1890 assert msg == null;
1891 // just dismiss the subwindow and load the given url.
1892 dismissSubWindow(currentTab);
1893 mWebView.loadUrl(url);
1894 }
1895 } else {
1896 // show mTabOverview if it is not there.
1897 if (mTabOverview == null) {
1898 // We have to delay the animation from the tab picker by the
1899 // length of the tab animation. Add a delay so the tab overview
1900 // can be shown before the second animation begins.
1901 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1902 tabPicker(false, ImageGrid.NEW_TAB, false);
1903 }
1904 // Animate from the Tab overview after any animations have
1905 // finished.
The Android Open Source Projected217d92008-12-17 18:05:52 -08001906 sendAnimateFromOverview(mTabControl.createNewTab(closeOnExit),
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001907 true, url, delay, msg);
1908 }
1909 } else if (url != null) {
1910 // We should not have a msg here.
1911 assert msg == null;
1912 if (mTabOverview != null && mAnimationCount == 0) {
1913 sendAnimateFromOverview(currentTab, false, url,
1914 TAB_OVERVIEW_DELAY, null);
1915 } else {
1916 // Get rid of the subwindow if it exists
1917 dismissSubWindow(currentTab);
1918 // Load the given url.
1919 mWebView.loadUrl(url);
1920 }
1921 }
1922 }
1923
1924 private Animation createTabAnimation(final AnimatingView view,
1925 final View cell, boolean scaleDown) {
1926 final AnimationSet set = new AnimationSet(true);
1927 final float scaleX = (float) cell.getWidth() / view.getWidth();
1928 final float scaleY = (float) cell.getHeight() / view.getHeight();
1929 if (scaleDown) {
1930 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
1931 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
1932 cell.getTop()));
1933 } else {
1934 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
1935 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
1936 cell.getTop(), 0));
1937 }
1938 set.setDuration(TAB_ANIMATION_DURATION);
1939 set.setInterpolator(new DecelerateInterpolator());
1940 return set;
1941 }
1942
1943 // Animate to the tab overview. currentIndex tells us which position to
1944 // animate to and newIndex is the position that should be selected after
1945 // the animation completes.
1946 // If remove is true, after the animation stops, a confirmation dialog will
1947 // be displayed to the user.
1948 private void animateToTabOverview(final int newIndex, final boolean remove,
1949 final AnimatingView view) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001950 // Find the view in the ImageGrid allowing for the "New Tab" cell.
1951 int position = mTabControl.getTabIndex(view.mTab);
1952 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
1953 position++;
1954 }
1955
1956 // Offset the tab position with the first visible position to get a
1957 // number between 0 and 3.
1958 position -= mTabOverview.getFirstVisiblePosition();
1959
1960 // Grab the view that we are going to animate to.
1961 final View v = mTabOverview.getChildAt(position);
1962
1963 final Animation.AnimationListener l =
1964 new Animation.AnimationListener() {
1965 public void onAnimationStart(Animation a) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08001966 mTabOverview.requestFocus();
1967 // Clear the listener so we don't trigger a tab
1968 // selection.
1969 mTabOverview.setListener(null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001970 }
1971 public void onAnimationRepeat(Animation a) {}
1972 public void onAnimationEnd(Animation a) {
1973 // We are no longer animating so decrement the count.
1974 mAnimationCount--;
1975 // Make the view GONE so that it will not draw between
1976 // now and when the Runnable is handled.
1977 view.setVisibility(View.GONE);
1978 // Post a runnable since we can't modify the view
1979 // hierarchy during this callback.
1980 mHandler.post(new Runnable() {
1981 public void run() {
1982 // Remove the AnimatingView.
1983 mContentView.removeView(view);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001984 // Make newIndex visible.
1985 mTabOverview.setCurrentIndex(newIndex);
1986 // Restore the listener.
1987 mTabOverview.setListener(mTabListener);
1988 // Change the menu to TAB_MENU if the
1989 // ImageGrid is interactive.
1990 if (mTabOverview.isLive()) {
1991 mMenuState = R.id.TAB_MENU;
1992 mTabOverview.requestFocus();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001993 }
1994 // If a remove was requested, remove the tab.
1995 if (remove) {
1996 // During a remove, the current tab has
1997 // already changed. Remember the current one
1998 // here.
1999 final TabControl.Tab currentTab =
2000 mTabControl.getCurrentTab();
2001 // Remove the tab at newIndex from
2002 // TabControl and the tab overview.
2003 final TabControl.Tab tab =
2004 mTabControl.getTab(newIndex);
2005 mTabControl.removeTab(tab);
2006 // Restore the current tab.
2007 if (currentTab != tab) {
2008 mTabControl.setCurrentTab(currentTab);
2009 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002010 mTabOverview.remove(newIndex);
2011 // Make the current tab visible.
2012 mTabOverview.setCurrentIndex(
2013 mTabControl.getCurrentIndex());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002014 }
2015 }
2016 });
2017 }
2018 };
2019
2020 // Do an animation if there is a view to animate to.
2021 if (v != null) {
2022 // Create our animation
2023 final Animation anim = createTabAnimation(view, v, true);
2024 anim.setAnimationListener(l);
2025 // Start animating
2026 view.startAnimation(anim);
2027 } else {
2028 // If something goes wrong and we didn't find a view to animate to,
2029 // just do everything here.
2030 l.onAnimationStart(null);
2031 l.onAnimationEnd(null);
2032 }
2033 }
2034
2035 // Animate from the tab picker. The index supplied is the index to animate
2036 // from.
2037 private void animateFromTabOverview(final AnimatingView view,
2038 final boolean newTab, final String url, final Message msg) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002039 // firstVisible is the first visible tab on the screen. This helps
2040 // to know which corner of the screen the selected tab is.
2041 int firstVisible = mTabOverview.getFirstVisiblePosition();
2042 // tabPosition is the 0-based index of of the tab being opened
2043 int tabPosition = mTabControl.getTabIndex(view.mTab);
2044 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2045 // Add one to make room for the "New Tab" cell.
2046 tabPosition++;
2047 }
2048 // If this is a new tab, animate from the "New Tab" cell.
2049 if (newTab) {
2050 tabPosition = 0;
2051 }
2052 // Location corresponds to the four corners of the screen.
2053 // A new tab or 0 is upper left, 0 for an old tab is upper
2054 // right, 1 is lower left, and 2 is lower right
2055 int location = tabPosition - firstVisible;
2056
2057 // Find the view at this location.
2058 final View v = mTabOverview.getChildAt(location);
2059
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002060 // Wait until the animation completes to load the url.
2061 final Animation.AnimationListener l =
2062 new Animation.AnimationListener() {
2063 public void onAnimationStart(Animation a) {}
2064 public void onAnimationRepeat(Animation a) {}
2065 public void onAnimationEnd(Animation a) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002066 mHandler.post(new Runnable() {
2067 public void run() {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002068 mContentView.removeView(view);
2069 // Dismiss the tab overview. If the cell at the
2070 // given location is null, set the fade
2071 // parameter to true.
2072 dismissTabOverview(v == null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002073 if (url != null) {
2074 // Dismiss the subwindow if one exists.
2075 dismissSubWindow(
2076 mTabControl.getCurrentTab());
2077 mWebView.loadUrl(url);
2078 }
2079 mMenuState = R.id.MAIN_MENU;
2080 // Resume regular updates.
2081 mWebView.resumeTimers();
2082 // Dispatch the message after the animation
2083 // completes.
2084 if (msg != null) {
2085 msg.sendToTarget();
2086 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002087 // The animation is done and the tab overview is
2088 // gone so allow key events and other animations
2089 // to begin.
2090 mAnimationCount--;
2091 // Reset all the title bar info.
2092 resetTitle();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002093 }
2094 });
2095 }
2096 };
2097
2098 if (v != null) {
2099 final Animation anim = createTabAnimation(view, v, false);
2100 // Set the listener and start animating
2101 anim.setAnimationListener(l);
2102 view.startAnimation(anim);
2103 // Make the view VISIBLE during the animation.
2104 view.setVisibility(View.VISIBLE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002105 } else {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002106 // Go ahead and load the url.
2107 l.onAnimationEnd(null);
2108 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002109 }
2110
2111 // Dismiss the tab overview applying a fade if needed.
2112 private void dismissTabOverview(final boolean fade) {
2113 if (fade) {
2114 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2115 anim.setDuration(500);
2116 anim.startNow();
2117 mTabOverview.startAnimation(anim);
2118 }
2119 // Just in case there was a problem with animating away from the tab
2120 // overview
2121 mWebView.setVisibility(View.VISIBLE);
2122 // Make the sub window container visible.
2123 if (mTabControl.getCurrentSubWindow() != null) {
2124 mTabControl.getCurrentTab().getSubWebViewContainer()
2125 .setVisibility(View.VISIBLE);
2126 }
2127 mContentView.removeView(mTabOverview);
2128 mTabOverview.clear();
2129 mTabOverview = null;
2130 mTabListener = null;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002131 }
2132
2133 private void openTab(String url) {
2134 if (mSettings.openInBackground()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002135 TabControl.Tab t = mTabControl.createNewTab(false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002136 if (t != null) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002137 t.getWebView().loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002138 }
2139 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002140 openTabAndShow(url, null, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002141 }
2142 }
2143
2144 private class Copy implements OnMenuItemClickListener {
2145 private CharSequence mText;
2146
2147 public boolean onMenuItemClick(MenuItem item) {
2148 copy(mText);
2149 return true;
2150 }
2151
2152 public Copy(CharSequence toCopy) {
2153 mText = toCopy;
2154 }
2155 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002156
2157 private class Download implements OnMenuItemClickListener {
2158 private String mText;
2159
2160 public boolean onMenuItemClick(MenuItem item) {
2161 onDownloadStartNoStream(mText, null, null, null, -1);
2162 return true;
2163 }
2164
2165 public Download(String toDownload) {
2166 mText = toDownload;
2167 }
2168 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002169
2170 private void copy(CharSequence text) {
2171 try {
2172 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2173 if (clip != null) {
2174 clip.setClipboardText(text);
2175 }
2176 } catch (android.os.RemoteException e) {
2177 Log.e(LOGTAG, "Copy failed", e);
2178 }
2179 }
2180
2181 /**
2182 * Resets the browser title-view to whatever it must be (for example, if we
2183 * load a page from history).
2184 */
2185 private void resetTitle() {
2186 resetLockIcon();
2187 resetTitleIconAndProgress();
2188 }
2189
2190 /**
2191 * Resets the browser title-view to whatever it must be
2192 * (for example, if we had a loading error)
2193 * When we have a new page, we call resetTitle, when we
2194 * have to reset the titlebar to whatever it used to be
2195 * (for example, if the user chose to stop loading), we
2196 * call resetTitleAndRevertLockIcon.
2197 */
2198 /* package */ void resetTitleAndRevertLockIcon() {
2199 revertLockIcon();
2200 resetTitleIconAndProgress();
2201 }
2202
2203 /**
2204 * Reset the title, favicon, and progress.
2205 */
2206 private void resetTitleIconAndProgress() {
2207 resetTitleAndIcon(mWebView);
2208 int progress = mWebView.getProgress();
2209 mInLoad = (progress != 100);
2210 updateInLoadMenuItems();
2211 mWebChromeClient.onProgressChanged(mWebView, progress);
2212 }
2213
2214 // Reset the title and the icon based on the given item.
2215 private void resetTitleAndIcon(WebView view) {
2216 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2217 if (item != null) {
2218 setUrlTitle(item.getUrl(), item.getTitle());
2219 setFavicon(item.getFavicon());
2220 } else {
2221 setUrlTitle(null, null);
2222 setFavicon(null);
2223 }
2224 }
2225
2226 /**
2227 * Sets a title composed of the URL and the title string.
2228 * @param url The URL of the site being loaded.
2229 * @param title The title of the site being loaded.
2230 */
2231 private void setUrlTitle(String url, String title) {
2232 mUrl = url;
2233 mTitle = title;
2234
The Android Open Source Projected217d92008-12-17 18:05:52 -08002235 // While the tab overview is animating or being shown, block changes
2236 // to the title.
2237 if (mAnimationCount == 0 && mTabOverview == null) {
2238 setTitle(buildUrlTitle(url, title));
2239 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002240 }
2241
2242 /**
2243 * Builds and returns the page title, which is some
2244 * combination of the page URL and title.
2245 * @param url The URL of the site being loaded.
2246 * @param title The title of the site being loaded.
2247 * @return The page title.
2248 */
2249 private String buildUrlTitle(String url, String title) {
2250 String urlTitle = "";
2251
2252 if (url != null) {
2253 String titleUrl = buildTitleUrl(url);
2254
2255 if (title != null && 0 < title.length()) {
2256 if (titleUrl != null && 0 < titleUrl.length()) {
2257 urlTitle = titleUrl + ": " + title;
2258 } else {
2259 urlTitle = title;
2260 }
2261 } else {
2262 if (titleUrl != null) {
2263 urlTitle = titleUrl;
2264 }
2265 }
2266 }
2267
2268 return urlTitle;
2269 }
2270
2271 /**
2272 * @param url The URL to build a title version of the URL from.
2273 * @return The title version of the URL or null if fails.
2274 * The title version of the URL can be either the URL hostname,
2275 * or the hostname with an "https://" prefix (for secure URLs),
2276 * or an empty string if, for example, the URL in question is a
2277 * file:// URL with no hostname.
2278 */
2279 private static String buildTitleUrl(String url) {
2280 String titleUrl = null;
2281
2282 if (url != null) {
2283 try {
2284 // parse the url string
2285 URL urlObj = new URL(url);
2286 if (urlObj != null) {
2287 titleUrl = "";
2288
2289 String protocol = urlObj.getProtocol();
2290 String host = urlObj.getHost();
2291
2292 if (host != null && 0 < host.length()) {
2293 titleUrl = host;
2294 if (protocol != null) {
2295 // if a secure site, add an "https://" prefix!
2296 if (protocol.equalsIgnoreCase("https")) {
2297 titleUrl = protocol + "://" + host;
2298 }
2299 }
2300 }
2301 }
2302 } catch (MalformedURLException e) {}
2303 }
2304
2305 return titleUrl;
2306 }
2307
2308 // Set the favicon in the title bar.
2309 private void setFavicon(Bitmap icon) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002310 // While the tab overview is animating or being shown, block changes to
2311 // the favicon.
2312 if (mAnimationCount > 0 || mTabOverview != null) {
2313 return;
2314 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002315 Drawable[] array = new Drawable[2];
2316 PaintDrawable p = new PaintDrawable(Color.WHITE);
2317 p.setCornerRadius(3f);
2318 array[0] = p;
2319 if (icon == null) {
2320 array[1] = mGenericFavicon;
2321 } else {
2322 array[1] = new BitmapDrawable(icon);
2323 }
2324 LayerDrawable d = new LayerDrawable(array);
2325 d.setLayerInset(1, 2, 2, 2, 2);
2326 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
2327 }
2328
2329 /**
2330 * Saves the current lock-icon state before resetting
2331 * the lock icon. If we have an error, we may need to
2332 * roll back to the previous state.
2333 */
2334 private void saveLockIcon() {
2335 mPrevLockType = mLockIconType;
2336 }
2337
2338 /**
2339 * Reverts the lock-icon state to the last saved state,
2340 * for example, if we had an error, and need to cancel
2341 * the load.
2342 */
2343 private void revertLockIcon() {
2344 mLockIconType = mPrevLockType;
2345
2346 if (Config.LOGV) {
2347 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2348 " revert lock icon to " + mLockIconType);
2349 }
2350
2351 updateLockIconImage(mLockIconType);
2352 }
2353
The Android Open Source Projected217d92008-12-17 18:05:52 -08002354 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002355 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2356 // Animate to the tab picker, remove the current tab, then
2357 // animate away from the tab picker to the parent WebView.
The Android Open Source Projected217d92008-12-17 18:05:52 -08002358 tabPicker(false, indexFrom, remove);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002359 // Change to the parent tab
2360 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2361 if (tab != null) {
2362 sendAnimateFromOverview(tab, false, null, delay, null);
2363 } else {
2364 // Send a message to open a new tab.
2365 mHandler.sendMessageDelayed(
2366 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2367 mSettings.getHomePage()), delay);
2368 }
2369 }
2370
2371 private void goBackOnePageOrQuit() {
2372 if (mWebView.canGoBack()) {
2373 mWebView.goBack();
2374 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002375 TabControl.Tab self = mTabControl.getCurrentTab();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002376 // Check to see if we are closing a window that was created by
2377 // another window. If so, we switch back to that window.
The Android Open Source Projected217d92008-12-17 18:05:52 -08002378 TabControl.Tab parent = self.getParentTab();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002379 if (parent != null) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002380 switchTabs(mTabControl.getCurrentIndex(),
2381 mTabControl.getTabIndex(parent), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002382 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002383 if (self.closeOnExit()) {
2384 if (mTabControl.getTabCount() == 1) {
2385 finish();
2386 return;
2387 }
2388 // call pauseWebView() now, we won't be able to call it in
2389 // onPause() as the mWebView won't be valid.
2390 pauseWebView();
2391 removeTabFromContentView(self);
2392 mTabControl.removeTab(self);
2393 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002394 /*
2395 * Instead of finishing the activity, simply push this to the back
2396 * of the stack and let ActivityManager to choose the foreground
2397 * activity. As BrowserActivity is singleTask, it will be always the
2398 * root of the task. So we can use either true or false for
2399 * moveTaskToBack().
2400 */
2401 moveTaskToBack(true);
2402 }
2403 }
2404 }
2405
2406 public KeyTracker.State onKeyTracker(int keyCode,
2407 KeyEvent event,
2408 KeyTracker.Stage stage,
2409 int duration) {
2410 // if onKeyTracker() is called after activity onStop()
2411 // because of accumulated key events,
2412 // we should ignore it as browser is not active any more.
2413 WebView topWindow = getTopWindow();
2414 if (topWindow == null)
2415 return KeyTracker.State.NOT_TRACKING;
2416
2417 if (keyCode == KeyEvent.KEYCODE_BACK) {
2418 // During animations, block the back key so that other animations
2419 // are not triggered and so that we don't end up destroying all the
2420 // WebViews before finishing the animation.
2421 if (mAnimationCount > 0) {
2422 return KeyTracker.State.DONE_TRACKING;
2423 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002424 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2425 loadHistory();
2426 return KeyTracker.State.DONE_TRACKING;
2427 } else if (stage == KeyTracker.Stage.UP) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002428 // FIXME: Currently, we do not have a notion of the
2429 // history picker for the subwindow, but maybe we
2430 // should?
2431 WebView subwindow = mTabControl.getCurrentSubWindow();
2432 if (subwindow != null) {
2433 if (subwindow.canGoBack()) {
2434 subwindow.goBack();
2435 } else {
2436 dismissSubWindow(mTabControl.getCurrentTab());
2437 }
2438 } else {
2439 goBackOnePageOrQuit();
2440 }
2441 return KeyTracker.State.DONE_TRACKING;
2442 }
2443 return KeyTracker.State.KEEP_TRACKING;
2444 }
2445 return KeyTracker.State.NOT_TRACKING;
2446 }
2447
2448 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2449 if (keyCode == KeyEvent.KEYCODE_MENU) {
2450 mMenuIsDown = true;
2451 }
2452 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2453 if (!handled) {
2454 switch (keyCode) {
2455 case KeyEvent.KEYCODE_SPACE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002456 if (event.isShiftPressed()) {
2457 getTopWindow().pageUp(false);
2458 } else {
2459 getTopWindow().pageDown(false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002460 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002461 handled = true;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002462 break;
2463
2464 default:
2465 break;
2466 }
2467 }
2468 return handled || super.onKeyDown(keyCode, event);
2469 }
2470
2471 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2472 if (keyCode == KeyEvent.KEYCODE_MENU) {
2473 mMenuIsDown = false;
2474 }
2475 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2476 }
2477
2478 private void stopLoading() {
2479 resetTitleAndRevertLockIcon();
2480 WebView w = getTopWindow();
2481 w.stopLoading();
2482 mWebViewClient.onPageFinished(w, w.getUrl());
2483
2484 cancelStopToast();
2485 mStopToast = Toast
2486 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2487 mStopToast.show();
2488 }
2489
2490 private void cancelStopToast() {
2491 if (mStopToast != null) {
2492 mStopToast.cancel();
2493 mStopToast = null;
2494 }
2495 }
2496
The Android Open Source Projected217d92008-12-17 18:05:52 -08002497 private void loadHistory() {
2498 Intent intent = new Intent(this, BrowserHistoryPage.class);
2499 intent.putExtra("maxTabsOpen",
2500 mTabControl.getTabCount() >= TabControl.MAX_TABS);
2501 startActivityForResult(intent, CLASSIC_HISTORY_PAGE);
2502 }
2503
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002504 // called by a non-UI thread to post the message
2505 public void postMessage(int what, int arg1, int arg2, Object obj) {
2506 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2507 }
2508
2509 // public message ids
2510 public final static int LOAD_URL = 1001;
2511 public final static int STOP_LOAD = 1002;
2512
2513 // Message Ids
2514 private static final int JS_CONFIRM = 101;
2515 private static final int FOCUS_NODE_HREF = 102;
The Android Open Source Projected217d92008-12-17 18:05:52 -08002516 private static final int CANCEL_CREDS_REQUEST = 103;
2517 private static final int ANIMATE_FROM_OVERVIEW = 104;
2518 private static final int ANIMATE_TO_OVERVIEW = 105;
2519 private static final int OPEN_TAB_AND_SHOW = 106;
2520 private static final int CHECK_MEMORY = 107;
2521 private static final int RELEASE_WAKELOCK = 108;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002522
2523 // Private handler for handling javascript and saving passwords
2524 private Handler mHandler = new Handler() {
2525
2526 public void handleMessage(Message msg) {
2527 switch (msg.what) {
2528 case JS_CONFIRM:
2529 JsResult res = (JsResult) msg.obj;
2530 if (msg.arg1 == 0) {
2531 res.cancel();
2532 } else {
2533 res.confirm();
2534 }
2535 break;
2536
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002537 case ANIMATE_FROM_OVERVIEW:
2538 final HashMap map = (HashMap) msg.obj;
2539 animateFromTabOverview((AnimatingView) map.get("view"),
2540 msg.arg1 == 1, (String) map.get("url"),
2541 (Message) map.get("msg"));
2542 break;
2543
2544 case ANIMATE_TO_OVERVIEW:
2545 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2546 (AnimatingView) msg.obj);
2547 break;
2548
2549 case OPEN_TAB_AND_SHOW:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002550 openTabAndShow((String) msg.obj, null, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002551 break;
2552
2553 case FOCUS_NODE_HREF:
2554 String url = (String) msg.getData().get("url");
2555 if (url == null || url.length() == 0) {
2556 break;
2557 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002558 HashMap focusNodeMap = (HashMap) msg.obj;
2559 WebView view = (WebView) focusNodeMap.get("webview");
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002560 // Only apply the action if the top window did not change.
2561 if (getTopWindow() != view) {
2562 break;
2563 }
2564 switch (msg.arg1) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002565 case R.id.open_context_menu_id:
2566 case R.id.view_image_context_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002567 loadURL(getTopWindow(), url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002568 break;
2569 case R.id.open_newtab_context_menu_id:
2570 openTab(url);
2571 break;
2572 case R.id.bookmark_context_menu_id:
2573 Intent intent = new Intent(BrowserActivity.this,
2574 AddBookmarkPage.class);
2575 intent.putExtra("url", url);
2576 startActivity(intent);
2577 break;
2578 case R.id.share_link_context_menu_id:
2579 Browser.sendString(BrowserActivity.this, url);
2580 break;
2581 case R.id.copy_link_context_menu_id:
2582 copy(url);
2583 break;
2584 case R.id.save_link_context_menu_id:
2585 case R.id.download_context_menu_id:
2586 onDownloadStartNoStream(url, null, null, null, -1);
2587 break;
2588 }
2589 break;
2590
2591 case LOAD_URL:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002592 loadURL(getTopWindow(), (String) msg.obj);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002593 break;
2594
2595 case STOP_LOAD:
2596 stopLoading();
2597 break;
2598
2599 case CANCEL_CREDS_REQUEST:
2600 resumeAfterCredentials();
2601 break;
2602
2603 case CHECK_MEMORY:
2604 // reschedule to check memory condition
2605 mHandler.removeMessages(CHECK_MEMORY);
2606 mHandler.sendMessageDelayed(mHandler.obtainMessage
2607 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2608 checkMemory();
2609 break;
2610
2611 case RELEASE_WAKELOCK:
2612 if (mWakeLock.isHeld()) {
2613 mWakeLock.release();
2614 }
2615 break;
2616 }
2617 }
2618 };
2619
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002620 // -------------------------------------------------------------------------
2621 // WebViewClient implementation.
2622 //-------------------------------------------------------------------------
2623
2624 // Use in overrideUrlLoading
2625 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2626 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2627 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2628 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2629
2630 /* package */ WebViewClient getWebViewClient() {
2631 return mWebViewClient;
2632 }
2633
The Android Open Source Projected217d92008-12-17 18:05:52 -08002634 private void updateIcon(String url, Bitmap icon) {
2635 if (icon != null) {
2636 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2637 url, icon);
2638 }
2639 setFavicon(icon);
2640 }
2641
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002642 private final WebViewClient mWebViewClient = new WebViewClient() {
2643 @Override
2644 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2645 resetLockIcon(url);
2646 setUrlTitle(url, null);
The Android Open Source Projected217d92008-12-17 18:05:52 -08002647 // Call updateIcon instead of setFavicon so the bookmark
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002648 // database can be updated.
The Android Open Source Projected217d92008-12-17 18:05:52 -08002649 updateIcon(url, favicon);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002650
2651 if (mSettings.isTracing() == true) {
2652 // FIXME: we should save the trace file somewhere other than data.
2653 // I can't use "/tmp" as it competes for system memory.
2654 File file = getDir("browserTrace", 0);
2655 String baseDir = file.getPath();
2656 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2657 String host;
2658 try {
2659 WebAddress uri = new WebAddress(url);
2660 host = uri.mHost;
2661 } catch (android.net.ParseException ex) {
2662 host = "unknown_host";
2663 }
2664 host = host.replace('.', '_');
2665 baseDir = baseDir + host;
2666 file = new File(baseDir+".data");
2667 if (file.exists() == true) {
2668 file.delete();
2669 }
2670 file = new File(baseDir+".key");
2671 if (file.exists() == true) {
2672 file.delete();
2673 }
2674 mInTrace = true;
2675 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2676 }
2677
2678 // Performance probe
2679 if (false) {
2680 mStart = SystemClock.uptimeMillis();
2681 mProcessStart = Process.getElapsedCpuTime();
2682 long[] sysCpu = new long[7];
2683 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2684 sysCpu, null)) {
2685 mUserStart = sysCpu[0] + sysCpu[1];
2686 mSystemStart = sysCpu[2];
2687 mIdleStart = sysCpu[3];
2688 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2689 }
2690 mUiStart = SystemClock.currentThreadTimeMillis();
2691 }
2692
2693 if (!mPageStarted) {
2694 mPageStarted = true;
2695 // if onResume() has been called, resumeWebView() does nothing.
2696 resumeWebView();
2697 }
2698
2699 // reset sync timer to avoid sync starts during loading a page
2700 CookieSyncManager.getInstance().resetSync();
2701
2702 mInLoad = true;
2703 updateInLoadMenuItems();
2704
2705 // schedule to check memory condition
2706 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
2707 CHECK_MEMORY_INTERVAL);
2708 }
2709
2710 @Override
2711 public void onPageFinished(WebView view, String url) {
2712 // Reset the title and icon in case we stopped a provisional
2713 // load.
2714 resetTitleAndIcon(view);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002715
2716 // Update the lock icon image only once we are done loading
2717 updateLockIconImage(mLockIconType);
2718
2719 // Performance probe
2720 if (false) {
2721 long[] sysCpu = new long[7];
2722 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2723 sysCpu, null)) {
2724 String uiInfo = "UI thread used "
2725 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2726 + " ms";
2727 if (Config.LOGD) {
2728 Log.d(LOGTAG, uiInfo);
2729 }
2730 //The string that gets written to the log
2731 String performanceString = "It took total "
2732 + (SystemClock.uptimeMillis() - mStart)
2733 + " ms clock time to load the page."
2734 + "\nbrowser process used "
2735 + (Process.getElapsedCpuTime() - mProcessStart)
2736 + " ms, user processes used "
2737 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2738 + " ms, kernel used "
2739 + (sysCpu[2] - mSystemStart) * 10
2740 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2741 + " ms and irq took "
2742 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2743 * 10 + " ms, " + uiInfo;
2744 if (Config.LOGD) {
2745 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2746 }
2747 if (url != null) {
2748 // strip the url to maintain consistency
2749 String newUrl = new String(url);
2750 if (newUrl.startsWith("http://www.")) {
2751 newUrl = newUrl.substring(11);
2752 } else if (newUrl.startsWith("http://")) {
2753 newUrl = newUrl.substring(7);
2754 } else if (newUrl.startsWith("https://www.")) {
2755 newUrl = newUrl.substring(12);
2756 } else if (newUrl.startsWith("https://")) {
2757 newUrl = newUrl.substring(8);
2758 }
2759 if (Config.LOGD) {
2760 Log.d(LOGTAG, newUrl + " loaded");
2761 }
2762 /*
2763 if (sWhiteList.contains(newUrl)) {
2764 // The string that gets pushed to the statistcs
2765 // service
2766 performanceString = performanceString
2767 + "\nWebpage: "
2768 + newUrl
2769 + "\nCarrier: "
2770 + android.os.SystemProperties
2771 .get("gsm.sim.operator.alpha");
2772 if (mWebView != null
2773 && mWebView.getContext() != null
2774 && mWebView.getContext().getSystemService(
2775 Context.CONNECTIVITY_SERVICE) != null) {
2776 ConnectivityManager cManager =
2777 (ConnectivityManager) mWebView
2778 .getContext().getSystemService(
2779 Context.CONNECTIVITY_SERVICE);
2780 NetworkInfo nInfo = cManager
2781 .getActiveNetworkInfo();
2782 if (nInfo != null) {
2783 performanceString = performanceString
2784 + "\nNetwork Type: "
2785 + nInfo.getType().toString();
2786 }
2787 }
2788 Checkin.logEvent(mResolver,
2789 Checkin.Events.Tag.WEBPAGE_LOAD,
2790 performanceString);
2791 Log.w(LOGTAG, "pushed to the statistics service");
2792 }
2793 */
2794 }
2795 }
2796 }
2797
2798 if (mInTrace) {
2799 mInTrace = false;
2800 Debug.stopMethodTracing();
2801 }
2802
2803 if (mPageStarted) {
2804 mPageStarted = false;
2805 // pauseWebView() will do nothing and return false if onPause()
2806 // is not called yet.
2807 if (pauseWebView()) {
2808 if (mWakeLock.isHeld()) {
2809 mHandler.removeMessages(RELEASE_WAKELOCK);
2810 mWakeLock.release();
2811 }
2812 }
2813 }
2814
2815 if (mInLoad) {
2816 mInLoad = false;
2817 updateInLoadMenuItems();
2818 }
2819
2820 mHandler.removeMessages(CHECK_MEMORY);
2821 checkMemory();
2822 }
2823
2824 // return true if want to hijack the url to let another app to handle it
2825 @Override
2826 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2827 if (url.startsWith(SCHEME_WTAI)) {
2828 // wtai://wp/mc;number
2829 // number=string(phone-number)
2830 if (url.startsWith(SCHEME_WTAI_MC)) {
2831 Intent intent = new Intent(Intent.ACTION_VIEW,
2832 Uri.parse(WebView.SCHEME_TEL +
2833 url.substring(SCHEME_WTAI_MC.length())));
2834 startActivity(intent);
2835 return true;
2836 }
2837 // wtai://wp/sd;dtmf
2838 // dtmf=string(dialstring)
2839 if (url.startsWith(SCHEME_WTAI_SD)) {
2840 // TODO
2841 // only send when there is active voice connection
2842 return false;
2843 }
2844 // wtai://wp/ap;number;name
2845 // number=string(phone-number)
2846 // name=string
2847 if (url.startsWith(SCHEME_WTAI_AP)) {
2848 // TODO
2849 return false;
2850 }
2851 }
2852
2853 Uri uri;
2854 try {
2855 uri = Uri.parse(url);
2856 } catch (IllegalArgumentException ex) {
2857 return false;
2858 }
2859
2860 // check whether other activities want to handle this url
2861 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
2862 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2863 try {
2864 if (startActivityIfNeeded(intent, -1)) {
2865 return true;
2866 }
2867 } catch (ActivityNotFoundException ex) {
2868 // ignore the error. If no application can handle the URL,
2869 // eg about:blank, assume the browser can handle it.
2870 }
2871
2872 if (mMenuIsDown) {
2873 openTab(url);
2874 closeOptionsMenu();
2875 return true;
2876 }
2877
2878 return false;
2879 }
2880
2881 /**
2882 * Updates the lock icon. This method is called when we discover another
2883 * resource to be loaded for this page (for example, javascript). While
2884 * we update the icon type, we do not update the lock icon itself until
2885 * we are done loading, it is slightly more secure this way.
2886 */
2887 @Override
2888 public void onLoadResource(WebView view, String url) {
2889 if (url != null && url.length() > 0) {
2890 // It is only if the page claims to be secure
2891 // that we may have to update the lock:
2892 if (mLockIconType == LOCK_ICON_SECURE) {
2893 // If NOT a 'safe' url, change the lock to mixed content!
2894 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2895 mLockIconType = LOCK_ICON_MIXED;
2896 if (Config.LOGV) {
2897 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2898 " updated lock icon to " + mLockIconType + " due to " + url);
2899 }
2900 }
2901 }
2902 }
2903 }
2904
2905 /**
2906 * Show the dialog, asking the user if they would like to continue after
2907 * an excessive number of HTTP redirects.
2908 */
2909 @Override
2910 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2911 final Message continueMsg) {
2912 new AlertDialog.Builder(BrowserActivity.this)
2913 .setTitle(R.string.browserFrameRedirect)
2914 .setMessage(R.string.browserFrame307Post)
2915 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2916 public void onClick(DialogInterface dialog, int which) {
2917 continueMsg.sendToTarget();
2918 }})
2919 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2920 public void onClick(DialogInterface dialog, int which) {
2921 cancelMsg.sendToTarget();
2922 }})
2923 .setOnCancelListener(new OnCancelListener() {
2924 public void onCancel(DialogInterface dialog) {
2925 cancelMsg.sendToTarget();
2926 }})
2927 .show();
2928 }
2929
2930 /**
2931 * Show a dialog informing the user of the network error reported by
2932 * WebCore.
2933 */
2934 @Override
2935 public void onReceivedError(WebView view, int errorCode,
2936 String description, String failingUrl) {
2937 if (errorCode != EventHandler.ERROR_LOOKUP &&
2938 errorCode != EventHandler.ERROR_CONNECT &&
2939 errorCode != EventHandler.ERROR_BAD_URL &&
The Android Open Source Projected217d92008-12-17 18:05:52 -08002940 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002941 errorCode != EventHandler.FILE_ERROR) {
2942 new AlertDialog.Builder(BrowserActivity.this)
2943 .setTitle((errorCode == EventHandler.FILE_NOT_FOUND_ERROR) ?
2944 R.string.browserFrameFileErrorLabel :
2945 R.string.browserFrameNetworkErrorLabel)
2946 .setMessage(description)
2947 .setPositiveButton(R.string.ok, null)
2948 .show();
2949 }
2950 Log.e(LOGTAG, "onReceivedError code:"+errorCode+" "+description);
2951
2952 // We need to reset the title after an error.
2953 resetTitleAndRevertLockIcon();
2954 }
2955
2956 /**
2957 * Check with the user if it is ok to resend POST data as the page they
2958 * are trying to navigate to is the result of a POST.
2959 */
2960 @Override
2961 public void onFormResubmission(WebView view, final Message dontResend,
2962 final Message resend) {
2963 new AlertDialog.Builder(BrowserActivity.this)
2964 .setTitle(R.string.browserFrameFormResubmitLabel)
2965 .setMessage(R.string.browserFrameFormResubmitMessage)
2966 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2967 public void onClick(DialogInterface dialog, int which) {
2968 resend.sendToTarget();
2969 }})
2970 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2971 public void onClick(DialogInterface dialog, int which) {
2972 dontResend.sendToTarget();
2973 }})
2974 .setOnCancelListener(new OnCancelListener() {
2975 public void onCancel(DialogInterface dialog) {
2976 dontResend.sendToTarget();
2977 }})
2978 .show();
2979 }
2980
2981 /**
2982 * Insert the url into the visited history database.
2983 * @param url The url to be inserted.
2984 * @param isReload True if this url is being reloaded.
2985 * FIXME: Not sure what to do when reloading the page.
2986 */
2987 @Override
2988 public void doUpdateVisitedHistory(WebView view, String url,
2989 boolean isReload) {
2990 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2991 return;
2992 }
2993 Browser.updateVisitedHistory(mResolver, url, true);
2994 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2995 }
2996
2997 /**
2998 * Displays SSL error(s) dialog to the user.
2999 */
3000 @Override
3001 public void onReceivedSslError(
3002 final WebView view, final SslErrorHandler handler, final SslError error) {
3003
3004 if (mSettings.showSecurityWarnings()) {
3005 final LayoutInflater factory =
3006 LayoutInflater.from(BrowserActivity.this);
3007 final View warningsView =
3008 factory.inflate(R.layout.ssl_warnings, null);
3009 final LinearLayout placeholder =
3010 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3011
3012 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3013 LinearLayout ll = (LinearLayout)factory
3014 .inflate(R.layout.ssl_warning, null);
3015 ((TextView)ll.findViewById(R.id.warning))
3016 .setText(R.string.ssl_untrusted);
3017 placeholder.addView(ll);
3018 }
3019
3020 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3021 LinearLayout ll = (LinearLayout)factory
3022 .inflate(R.layout.ssl_warning, null);
3023 ((TextView)ll.findViewById(R.id.warning))
3024 .setText(R.string.ssl_mismatch);
3025 placeholder.addView(ll);
3026 }
3027
3028 if (error.hasError(SslError.SSL_EXPIRED)) {
3029 LinearLayout ll = (LinearLayout)factory
3030 .inflate(R.layout.ssl_warning, null);
3031 ((TextView)ll.findViewById(R.id.warning))
3032 .setText(R.string.ssl_expired);
3033 placeholder.addView(ll);
3034 }
3035
3036 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3037 LinearLayout ll = (LinearLayout)factory
3038 .inflate(R.layout.ssl_warning, null);
3039 ((TextView)ll.findViewById(R.id.warning))
3040 .setText(R.string.ssl_not_yet_valid);
3041 placeholder.addView(ll);
3042 }
3043
3044 new AlertDialog.Builder(BrowserActivity.this)
3045 .setTitle(R.string.security_warning)
3046 .setIcon(R.drawable.ic_dialog_alert)
3047 .setView(warningsView)
3048 .setPositiveButton(R.string.ssl_continue,
3049 new DialogInterface.OnClickListener() {
3050 public void onClick(DialogInterface dialog, int whichButton) {
3051 handler.proceed();
3052 }
3053 })
3054 .setNeutralButton(R.string.view_certificate,
3055 new DialogInterface.OnClickListener() {
3056 public void onClick(DialogInterface dialog, int whichButton) {
3057 showSSLCertificateOnError(view, handler, error);
3058 }
3059 })
3060 .setNegativeButton(R.string.cancel,
3061 new DialogInterface.OnClickListener() {
3062 public void onClick(DialogInterface dialog, int whichButton) {
3063 handler.cancel();
3064 BrowserActivity.this.resetTitleAndRevertLockIcon();
3065 }
3066 })
3067 .setOnCancelListener(
3068 new DialogInterface.OnCancelListener() {
3069 public void onCancel(DialogInterface dialog) {
3070 handler.cancel();
3071 BrowserActivity.this.resetTitleAndRevertLockIcon();
3072 }
3073 })
3074 .show();
3075 } else {
3076 handler.proceed();
3077 }
3078 }
3079
3080 /**
3081 * Handles an HTTP authentication request.
3082 *
3083 * @param handler The authentication handler
3084 * @param host The host
3085 * @param realm The realm
3086 */
3087 @Override
3088 public void onReceivedHttpAuthRequest(WebView view,
3089 final HttpAuthHandler handler, final String host, final String realm) {
3090 String username = null;
3091 String password = null;
3092
3093 boolean reuseHttpAuthUsernamePassword =
3094 handler.useHttpAuthUsernamePassword();
3095
3096 if (reuseHttpAuthUsernamePassword) {
3097 String[] credentials =
3098 mWebView.getHttpAuthUsernamePassword(host, realm);
3099 if (credentials != null && credentials.length == 2) {
3100 username = credentials[0];
3101 password = credentials[1];
3102 }
3103 }
3104
3105 if (username != null && password != null) {
3106 handler.proceed(username, password);
3107 } else {
3108 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3109 }
3110 }
3111
3112 @Override
3113 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3114 if (mMenuIsDown) {
3115 // only check shortcut key when MENU is held
3116 return getWindow().isShortcutKey(event.getKeyCode(), event);
3117 } else {
3118 return false;
3119 }
3120 }
3121
3122 @Override
3123 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3124 if (event.isDown()) {
3125 mKeyTracker.doKeyDown(event.getKeyCode(), event);
3126 } else {
3127 mKeyTracker.doKeyUp(event.getKeyCode(), event);
3128 }
3129 }
3130 };
3131
3132 //--------------------------------------------------------------------------
3133 // WebChromeClient implementation
3134 //--------------------------------------------------------------------------
3135
3136 /* package */ WebChromeClient getWebChromeClient() {
3137 return mWebChromeClient;
3138 }
3139
3140 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3141 // Helper method to create a new tab or sub window.
3142 private void createWindow(final boolean dialog, final Message msg) {
3143 if (dialog) {
3144 mTabControl.createSubWindow();
3145 final TabControl.Tab t = mTabControl.getCurrentTab();
3146 attachSubWindow(t);
3147 WebView.WebViewTransport transport =
3148 (WebView.WebViewTransport) msg.obj;
3149 transport.setWebView(t.getSubWebView());
3150 msg.sendToTarget();
3151 } else {
3152 final TabControl.Tab parent = mTabControl.getCurrentTab();
3153 // openTabAndShow will dispatch the message after creating the
3154 // new WebView. This will prevent another request from coming
3155 // in during the animation.
The Android Open Source Projected217d92008-12-17 18:05:52 -08003156 openTabAndShow(null, msg, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003157 parent.addChildTab(mTabControl.getCurrentTab());
3158 WebView.WebViewTransport transport =
3159 (WebView.WebViewTransport) msg.obj;
3160 transport.setWebView(mWebView);
3161 }
3162 }
3163
3164 @Override
3165 public boolean onCreateWindow(WebView view, final boolean dialog,
3166 final boolean userGesture, final Message resultMsg) {
3167 // Ignore these requests during tab animations or if the tab
3168 // overview is showing.
3169 if (mAnimationCount > 0 || mTabOverview != null) {
3170 return false;
3171 }
3172 // Short-circuit if we can't create any more tabs or sub windows.
3173 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3174 new AlertDialog.Builder(BrowserActivity.this)
3175 .setTitle(R.string.too_many_subwindows_dialog_title)
3176 .setIcon(R.drawable.ic_dialog_alert)
3177 .setMessage(R.string.too_many_subwindows_dialog_message)
3178 .setPositiveButton(R.string.ok, null)
3179 .show();
3180 return false;
3181 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3182 new AlertDialog.Builder(BrowserActivity.this)
3183 .setTitle(R.string.too_many_windows_dialog_title)
3184 .setIcon(R.drawable.ic_dialog_alert)
3185 .setMessage(R.string.too_many_windows_dialog_message)
3186 .setPositiveButton(R.string.ok, null)
3187 .show();
3188 return false;
3189 }
3190
3191 // Short-circuit if this was a user gesture.
3192 if (userGesture) {
3193 // createWindow will call openTabAndShow for new Windows and
3194 // that will call tabPicker which will increment
3195 // mAnimationCount.
3196 createWindow(dialog, resultMsg);
3197 return true;
3198 }
3199
3200 // Allow the popup and create the appropriate window.
3201 final AlertDialog.OnClickListener allowListener =
3202 new AlertDialog.OnClickListener() {
3203 public void onClick(DialogInterface d,
3204 int which) {
3205 // Same comment as above for setting
3206 // mAnimationCount.
3207 createWindow(dialog, resultMsg);
3208 // Since we incremented mAnimationCount while the
3209 // dialog was up, we have to decrement it here.
3210 mAnimationCount--;
3211 }
3212 };
3213
3214 // Block the popup by returning a null WebView.
3215 final AlertDialog.OnClickListener blockListener =
3216 new AlertDialog.OnClickListener() {
3217 public void onClick(DialogInterface d, int which) {
3218 resultMsg.sendToTarget();
3219 // We are not going to trigger an animation so
3220 // unblock keys and animation requests.
3221 mAnimationCount--;
3222 }
3223 };
3224
3225 // Build a confirmation dialog to display to the user.
3226 final AlertDialog d =
3227 new AlertDialog.Builder(BrowserActivity.this)
3228 .setTitle(R.string.attention)
3229 .setIcon(R.drawable.ic_dialog_alert)
3230 .setMessage(R.string.popup_window_attempt)
3231 .setPositiveButton(R.string.allow, allowListener)
3232 .setNegativeButton(R.string.block, blockListener)
3233 .setCancelable(false)
3234 .create();
3235
3236 // Show the confirmation dialog.
3237 d.show();
3238 // We want to increment mAnimationCount here to prevent a
3239 // potential race condition. If the user allows a pop-up from a
3240 // site and that pop-up then triggers another pop-up, it is
3241 // possible to get the BACK key between here and when the dialog
3242 // appears.
3243 mAnimationCount++;
3244 return true;
3245 }
3246
3247 @Override
3248 public void onCloseWindow(WebView window) {
3249 final int currentIndex = mTabControl.getCurrentIndex();
3250 final TabControl.Tab parent =
3251 mTabControl.getCurrentTab().getParentTab();
3252 if (parent != null) {
3253 // JavaScript can only close popup window.
The Android Open Source Projected217d92008-12-17 18:05:52 -08003254 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003255 }
3256 }
3257
3258 @Override
3259 public void onProgressChanged(WebView view, int newProgress) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003260 // Block progress updates to the title bar while the tab overview
3261 // is animating or being displayed.
3262 if (mAnimationCount == 0 && mTabOverview == null) {
3263 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3264 newProgress * 100);
3265 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003266
3267 if (newProgress == 100) {
3268 // onProgressChanged() is called for sub-frame too while
3269 // onPageFinished() is only called for the main frame. sync
3270 // cookie and cache promptly here.
3271 CookieSyncManager.getInstance().sync();
3272 }
3273 }
3274
3275 @Override
3276 public void onReceivedTitle(WebView view, String title) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003277 String url = view.getOriginalUrl();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003278
3279 // here, if url is null, we want to reset the title
3280 setUrlTitle(url, title);
3281
3282 if (url == null ||
3283 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3284 return;
3285 }
3286 if (url.startsWith("http://www.")) {
3287 url = url.substring(11);
3288 } else if (url.startsWith("http://")) {
3289 url = url.substring(4);
3290 }
3291 try {
3292 url = "%" + url;
3293 String [] selArgs = new String[] { url };
3294
3295 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3296 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3297 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3298 Browser.HISTORY_PROJECTION, where, selArgs, null);
3299 if (c.moveToFirst()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003300 if (Config.LOGV) {
3301 Log.v(LOGTAG, "updating cursor");
3302 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003303 // Current implementation of database only has one entry per
3304 // url.
3305 int titleIndex =
3306 c.getColumnIndex(Browser.BookmarkColumns.TITLE);
3307 c.updateString(titleIndex, title);
3308 c.commitUpdates();
3309 }
3310 c.close();
3311 } catch (IllegalStateException e) {
3312 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3313 } catch (SQLiteException ex) {
3314 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3315 }
3316 }
3317
3318 @Override
3319 public void onReceivedIcon(WebView view, Bitmap icon) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003320 updateIcon(view.getUrl(), icon);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003321 }
3322
3323 //----------------------------------------------------------------------
3324 // JavaScript functions.
3325 //----------------------------------------------------------------------
3326
3327 // Show an alert to the user.
3328 @Override
3329 public boolean onJsAlert(WebView view, String url, String message,
3330 JsResult result) {
3331 String title = url;
3332 if (URLUtil.isDataUrl(url)) {
3333 // For data: urls, we just display 'JavaScript' similar to
3334 // Safari.
3335 title = getString(R.string.js_dialog_title_default);
3336 } else {
3337 try {
3338 URL aUrl = new URL(url);
3339 // Example: "The page at 'http://www.mit.edu' says:"
3340 title = getText(R.string.js_dialog_title_prefix)
3341 + " '"
3342 + (aUrl.getProtocol() + "://" + aUrl.getHost())
3343 + "' "
3344 + getText(R.string.js_dialog_title_suffix);
3345 } catch (MalformedURLException ex) {
3346 // do nothing. just use the url passed as the title
3347 }
3348 }
3349 final JsResult res = result;
3350 new AlertDialog.Builder(BrowserActivity.this)
3351 .setTitle(title)
3352 .setMessage(message)
3353 .setPositiveButton(R.string.ok,
3354 new AlertDialog.OnClickListener() {
3355 public void onClick(DialogInterface dialog,
3356 int which) {
3357 res.confirm();
3358 }
3359 })
3360 .setCancelable(false)
3361 .show();
3362 return true;
3363 }
3364
3365 @Override
3366 public boolean onJsConfirm(WebView view, String url, String message,
3367 final JsResult result) {
3368 String title = url;
3369 try {
3370 URL aUrl = new URL(url);
3371 // Example: "The page at 'http://www.mit.edu' says:"
3372 title = getText(R.string.js_dialog_title_prefix)
3373 + " '"
3374 + (aUrl.getProtocol() + "://" + aUrl.getHost())
3375 + "' "
3376 + getText(R.string.js_dialog_title_suffix);
3377 } catch (MalformedURLException ex) {
3378 // do nothing. just use the url passed as the title
3379 }
3380 new AlertDialog.Builder(BrowserActivity.this)
3381 .setTitle(title)
3382 .setMessage(message)
3383 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3384 public void onClick(DialogInterface dialog, int which) {
3385 mHandler.obtainMessage(JS_CONFIRM, 1, 0, result).sendToTarget();
3386 }})
3387 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3388 public void onClick(DialogInterface dialog, int which) {
3389 mHandler.obtainMessage(JS_CONFIRM, 0, 0, result).sendToTarget();
3390 }})
3391 .show();
3392 // Return true so WebView knows we will handle the confirm.
3393 return true;
3394 }
3395
3396 @Override
3397 public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
3398 final JsPromptResult result) {
3399 String title = url;
3400 try {
3401 URL aUrl = new URL(url);
3402 // Example: "The page at 'http://www.mit.edu' says:"
3403 title = getText(R.string.js_dialog_title_prefix)
3404 + " '"
3405 + (aUrl.getProtocol() + "://" + aUrl.getHost())
3406 + "' "
3407 + getText(R.string.js_dialog_title_suffix);
3408 } catch (MalformedURLException ex) {
3409 // do nothing, just use the url passed as the title
3410 }
3411
3412 final LayoutInflater factory = LayoutInflater.from(BrowserActivity.this);
3413 final View v = factory.inflate(R.layout.js_prompt, null);
3414 ((TextView)v.findViewById(R.id.message)).setText(message);
3415 ((EditText)v.findViewById(R.id.value)).setText(defaultValue);
3416
3417 new AlertDialog.Builder(BrowserActivity.this)
3418 .setTitle(title)
3419 .setView(v)
3420 .setPositiveButton(R.string.ok,
3421 new DialogInterface.OnClickListener() {
3422 public void onClick(DialogInterface dialog, int whichButton) {
3423 String value = ((EditText)v.findViewById(R.id.value)).getText()
3424 .toString();
3425 result.confirm(value);
3426 }
3427 })
3428 .setNegativeButton(R.string.cancel,
3429 new DialogInterface.OnClickListener() {
3430 public void onClick(DialogInterface dialog, int whichButton) {
3431 result.cancel();
3432 }
3433 })
3434 .setOnCancelListener(
3435 new DialogInterface.OnCancelListener() {
3436 public void onCancel(DialogInterface dialog) {
3437 result.cancel();
3438 }
3439 })
3440 .show();
3441
3442 // Return true so WebView knows we will handle the prompt.
3443 return true;
3444 }
3445
3446 @Override
3447 public boolean onJsBeforeUnload(WebView view, String url,
3448 String message, final JsResult result) {
3449 final String m =
3450 getString(R.string.js_dialog_before_unload, message);
3451 new AlertDialog.Builder(BrowserActivity.this)
3452 .setMessage(m)
3453 .setPositiveButton(R.string.ok,
3454 new DialogInterface.OnClickListener() {
3455 public void onClick(DialogInterface dialog,
3456 int which) {
3457 // Use JS_CONFIRM since it has the same
3458 // behavior we want here.
3459 mHandler.obtainMessage(JS_CONFIRM, 1, 0,
3460 result).sendToTarget();
3461 }})
3462 .setNegativeButton(R.string.cancel,
3463 new DialogInterface.OnClickListener() {
3464 public void onClick(DialogInterface dialog,
3465 int which) {
3466 // Use JS_CONFIRM since it has the same
3467 // behavior we want here.
3468 mHandler.obtainMessage(JS_CONFIRM, 0, 0,
3469 result).sendToTarget();
3470 }})
3471 .show();
3472 // Return true so WebView knows we will handle the dialog.
3473 return true;
3474 }
3475 };
3476
3477 /**
3478 * Notify the host application a download should be done, or that
3479 * the data should be streamed if a streaming viewer is available.
3480 * @param url The full url to the content that should be downloaded
3481 * @param contentDisposition Content-disposition http header, if
3482 * present.
3483 * @param mimetype The mimetype of the content reported by the server
3484 * @param contentLength The file size reported by the server
3485 */
3486 public void onDownloadStart(String url, String userAgent,
3487 String contentDisposition, String mimetype, long contentLength) {
3488 // if we're dealing wih A/V content that's not explicitly marked
3489 // for download, check if it's streamable.
3490 if (contentDisposition == null
3491 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3492 // query the package manager to see if there's a registered handler
3493 // that matches.
3494 Intent intent = new Intent(Intent.ACTION_VIEW);
3495 intent.setDataAndType(Uri.parse(url), mimetype);
3496 if (getPackageManager().queryIntentActivities(intent,
3497 PackageManager.MATCH_DEFAULT_ONLY).size() != 0) {
3498 // someone knows how to handle this mime type with this scheme, don't download.
3499 try {
3500 startActivity(intent);
3501 return;
3502 } catch (ActivityNotFoundException ex) {
3503 if (Config.LOGD) {
3504 Log.d(LOGTAG, "activity not found for " + mimetype
3505 + " over " + Uri.parse(url).getScheme(), ex);
3506 }
3507 // Best behavior is to fall back to a download in this case
3508 }
3509 }
3510 }
3511 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3512 }
3513
3514 /**
3515 * Notify the host application a download should be done, even if there
3516 * is a streaming viewer available for thise type.
3517 * @param url The full url to the content that should be downloaded
3518 * @param contentDisposition Content-disposition http header, if
3519 * present.
3520 * @param mimetype The mimetype of the content reported by the server
3521 * @param contentLength The file size reported by the server
3522 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08003523 /*package */ void onDownloadStartNoStream(String url, String userAgent,
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003524 String contentDisposition, String mimetype, long contentLength) {
3525
3526 String filename = URLUtil.guessFileName(url,
3527 contentDisposition, mimetype);
3528
3529 // Check to see if we have an SDCard
The Android Open Source Projected217d92008-12-17 18:05:52 -08003530 String status = Environment.getExternalStorageState();
3531 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3532 int title;
3533 String msg;
3534
3535 // Check to see if the SDCard is busy, same as the music app
3536 if (status.equals(Environment.MEDIA_SHARED)) {
3537 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3538 title = R.string.download_sdcard_busy_dlg_title;
3539 } else {
3540 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3541 title = R.string.download_no_sdcard_dlg_title;
3542 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003543
3544 new AlertDialog.Builder(this)
The Android Open Source Projected217d92008-12-17 18:05:52 -08003545 .setTitle(title)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003546 .setIcon(R.drawable.ic_dialog_alert)
3547 .setMessage(msg)
3548 .setPositiveButton(R.string.ok, null)
3549 .show();
3550 return;
3551 }
3552
3553 String cookies = CookieManager.getInstance().getCookie(url);
3554
3555 ContentValues values = new ContentValues();
3556 values.put(Downloads.URI, url);
3557 values.put(Downloads.COOKIE_DATA, cookies);
3558 values.put(Downloads.USER_AGENT, userAgent);
3559 values.put(Downloads.NOTIFICATION_PACKAGE,
3560 getPackageName());
3561 values.put(Downloads.NOTIFICATION_CLASS,
3562 BrowserDownloadPage.class.getCanonicalName());
3563 values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3564 values.put(Downloads.MIMETYPE, mimetype);
3565 values.put(Downloads.FILENAME_HINT, filename);
3566 values.put(Downloads.DESCRIPTION, Uri.parse(url).getHost());
3567 if (contentLength > 0) {
3568 values.put(Downloads.TOTAL_BYTES, contentLength);
3569 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08003570 if (mimetype == null) {
3571 // We must have long pressed on a link or image to download it. We
3572 // are not sure of the mimetype in this case, so do a head request
3573 new FetchUrlMimeType(this).execute(values);
3574 } else {
3575 final Uri contentUri =
3576 getContentResolver().insert(Downloads.CONTENT_URI, values);
3577 viewDownloads(contentUri);
3578 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003579
3580 }
3581
3582 /**
3583 * Resets the lock icon. This method is called when we start a new load and
3584 * know the url to be loaded.
3585 */
3586 private void resetLockIcon(String url) {
3587 // Save the lock-icon state (we revert to it if the load gets cancelled)
3588 saveLockIcon();
3589
3590 mLockIconType = LOCK_ICON_UNSECURE;
3591 if (URLUtil.isHttpsUrl(url)) {
3592 mLockIconType = LOCK_ICON_SECURE;
3593 if (Config.LOGV) {
3594 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3595 " reset lock icon to " + mLockIconType);
3596 }
3597 }
3598
3599 updateLockIconImage(LOCK_ICON_UNSECURE);
3600 }
3601
3602 /**
3603 * Resets the lock icon. This method is called when the icon needs to be
3604 * reset but we do not know whether we are loading a secure or not secure
3605 * page.
3606 */
3607 private void resetLockIcon() {
3608 // Save the lock-icon state (we revert to it if the load gets cancelled)
3609 saveLockIcon();
3610
3611 mLockIconType = LOCK_ICON_UNSECURE;
3612
3613 if (Config.LOGV) {
3614 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3615 " reset lock icon to " + mLockIconType);
3616 }
3617
3618 updateLockIconImage(LOCK_ICON_UNSECURE);
3619 }
3620
3621 /**
3622 * Updates the lock-icon image in the title-bar.
3623 */
3624 private void updateLockIconImage(int lockIconType) {
3625 Drawable d = null;
3626 if (lockIconType == LOCK_ICON_SECURE) {
3627 d = mSecLockIcon;
3628 } else if (lockIconType == LOCK_ICON_MIXED) {
3629 d = mMixLockIcon;
3630 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08003631 // If the tab overview is animating or being shown, do not update the
3632 // lock icon.
3633 if (mAnimationCount == 0 && mTabOverview == null) {
3634 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
3635 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003636 }
3637
3638 /**
3639 * Displays a page-info dialog.
The Android Open Source Projected217d92008-12-17 18:05:52 -08003640 * @param tab The tab to show info about
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003641 * @param fromShowSSLCertificateOnError The flag that indicates whether
3642 * this dialog was opened from the SSL-certificate-on-error dialog or
3643 * not. This is important, since we need to know whether to return to
3644 * the parent dialog or simply dismiss.
3645 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08003646 private void showPageInfo(final TabControl.Tab tab,
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003647 final boolean fromShowSSLCertificateOnError) {
3648 final LayoutInflater factory = LayoutInflater
3649 .from(this);
3650
3651 final View pageInfoView = factory.inflate(R.layout.page_info, null);
The Android Open Source Projected217d92008-12-17 18:05:52 -08003652
3653 final WebView view = tab.getWebView();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003654
3655 String url = null;
3656 String title = null;
3657
The Android Open Source Projected217d92008-12-17 18:05:52 -08003658 if (view == null) {
3659 url = tab.getUrl();
3660 title = tab.getTitle();
3661 }else if (view == mWebView) {
3662 // Use the cached title and url if this is the current WebView
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003663 url = mUrl;
3664 title = mTitle;
3665 } else {
3666 url = view.getUrl();
3667 title = view.getTitle();
3668 }
3669
3670 if (url == null) {
3671 url = "";
3672 }
3673 if (title == null) {
3674 title = "";
3675 }
3676
3677 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3678 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3679
The Android Open Source Projected217d92008-12-17 18:05:52 -08003680 mPageInfoView = tab;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003681 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3682
3683 AlertDialog.Builder alertDialogBuilder =
3684 new AlertDialog.Builder(this)
3685 .setTitle(R.string.page_info).setIcon(R.drawable.ic_dialog_info)
3686 .setView(pageInfoView)
3687 .setPositiveButton(
3688 R.string.ok,
3689 new DialogInterface.OnClickListener() {
3690 public void onClick(DialogInterface dialog,
3691 int whichButton) {
3692 mPageInfoDialog = null;
3693 mPageInfoView = null;
3694 mPageInfoFromShowSSLCertificateOnError = null;
3695
3696 // if we came here from the SSL error dialog
3697 if (fromShowSSLCertificateOnError) {
3698 // go back to the SSL error dialog
3699 showSSLCertificateOnError(
3700 mSSLCertificateOnErrorView,
3701 mSSLCertificateOnErrorHandler,
3702 mSSLCertificateOnErrorError);
3703 }
3704 }
3705 })
3706 .setOnCancelListener(
3707 new DialogInterface.OnCancelListener() {
3708 public void onCancel(DialogInterface dialog) {
3709 mPageInfoDialog = null;
3710 mPageInfoView = null;
3711 mPageInfoFromShowSSLCertificateOnError = null;
3712
3713 // if we came here from the SSL error dialog
3714 if (fromShowSSLCertificateOnError) {
3715 // go back to the SSL error dialog
3716 showSSLCertificateOnError(
3717 mSSLCertificateOnErrorView,
3718 mSSLCertificateOnErrorHandler,
3719 mSSLCertificateOnErrorError);
3720 }
3721 }
3722 });
3723
3724 // if we have a main top-level page SSL certificate set or a certificate
3725 // error
The Android Open Source Projected217d92008-12-17 18:05:52 -08003726 if (fromShowSSLCertificateOnError ||
3727 (view != null && view.getCertificate() != null)) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003728 // add a 'View Certificate' button
3729 alertDialogBuilder.setNeutralButton(
3730 R.string.view_certificate,
3731 new DialogInterface.OnClickListener() {
3732 public void onClick(DialogInterface dialog,
3733 int whichButton) {
3734 mPageInfoDialog = null;
3735 mPageInfoView = null;
3736 mPageInfoFromShowSSLCertificateOnError = null;
3737
3738 // if we came here from the SSL error dialog
3739 if (fromShowSSLCertificateOnError) {
3740 // go back to the SSL error dialog
3741 showSSLCertificateOnError(
3742 mSSLCertificateOnErrorView,
3743 mSSLCertificateOnErrorHandler,
3744 mSSLCertificateOnErrorError);
3745 } else {
3746 // otherwise, display the top-most certificate from
3747 // the chain
3748 if (view.getCertificate() != null) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003749 showSSLCertificate(tab);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003750 }
3751 }
3752 }
3753 });
3754 }
3755
3756 mPageInfoDialog = alertDialogBuilder.show();
3757 }
3758
3759 /**
3760 * Displays the main top-level page SSL certificate dialog
3761 * (accessible from the Page-Info dialog).
The Android Open Source Projected217d92008-12-17 18:05:52 -08003762 * @param tab The tab to show certificate for.
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003763 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08003764 private void showSSLCertificate(final TabControl.Tab tab) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003765 final View certificateView =
3766 inflateCertificateView(mWebView.getCertificate());
3767 if (certificateView == null) {
3768 return;
3769 }
3770
3771 LayoutInflater factory = LayoutInflater.from(this);
3772
3773 final LinearLayout placeholder =
3774 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3775
3776 LinearLayout ll = (LinearLayout) factory.inflate(
3777 R.layout.ssl_success, placeholder);
3778 ((TextView)ll.findViewById(R.id.success))
3779 .setText(R.string.ssl_certificate_is_valid);
3780
The Android Open Source Projected217d92008-12-17 18:05:52 -08003781 mSSLCertificateView = tab;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003782 mSSLCertificateDialog =
3783 new AlertDialog.Builder(this)
3784 .setTitle(R.string.ssl_certificate).setIcon(
3785 R.drawable.ic_dialog_browser_certificate_secure)
3786 .setView(certificateView)
3787 .setPositiveButton(R.string.ok,
3788 new DialogInterface.OnClickListener() {
3789 public void onClick(DialogInterface dialog,
3790 int whichButton) {
3791 mSSLCertificateDialog = null;
3792 mSSLCertificateView = null;
3793
The Android Open Source Projected217d92008-12-17 18:05:52 -08003794 showPageInfo(tab, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003795 }
3796 })
3797 .setOnCancelListener(
3798 new DialogInterface.OnCancelListener() {
3799 public void onCancel(DialogInterface dialog) {
3800 mSSLCertificateDialog = null;
3801 mSSLCertificateView = null;
3802
The Android Open Source Projected217d92008-12-17 18:05:52 -08003803 showPageInfo(tab, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003804 }
3805 })
3806 .show();
3807 }
3808
3809 /**
3810 * Displays the SSL error certificate dialog.
3811 * @param view The target web-view.
3812 * @param handler The SSL error handler responsible for cancelling the
3813 * connection that resulted in an SSL error or proceeding per user request.
3814 * @param error The SSL error object.
3815 */
3816 private void showSSLCertificateOnError(
3817 final WebView view, final SslErrorHandler handler, final SslError error) {
3818
3819 final View certificateView =
3820 inflateCertificateView(error.getCertificate());
3821 if (certificateView == null) {
3822 return;
3823 }
3824
3825 LayoutInflater factory = LayoutInflater.from(this);
3826
3827 final LinearLayout placeholder =
3828 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3829
3830 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3831 LinearLayout ll = (LinearLayout)factory
3832 .inflate(R.layout.ssl_warning, placeholder);
3833 ((TextView)ll.findViewById(R.id.warning))
3834 .setText(R.string.ssl_untrusted);
3835 }
3836
3837 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3838 LinearLayout ll = (LinearLayout)factory
3839 .inflate(R.layout.ssl_warning, placeholder);
3840 ((TextView)ll.findViewById(R.id.warning))
3841 .setText(R.string.ssl_mismatch);
3842 }
3843
3844 if (error.hasError(SslError.SSL_EXPIRED)) {
3845 LinearLayout ll = (LinearLayout)factory
3846 .inflate(R.layout.ssl_warning, placeholder);
3847 ((TextView)ll.findViewById(R.id.warning))
3848 .setText(R.string.ssl_expired);
3849 }
3850
3851 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3852 LinearLayout ll = (LinearLayout)factory
3853 .inflate(R.layout.ssl_warning, placeholder);
3854 ((TextView)ll.findViewById(R.id.warning))
3855 .setText(R.string.ssl_not_yet_valid);
3856 }
3857
3858 mSSLCertificateOnErrorHandler = handler;
3859 mSSLCertificateOnErrorView = view;
3860 mSSLCertificateOnErrorError = error;
3861 mSSLCertificateOnErrorDialog =
3862 new AlertDialog.Builder(this)
3863 .setTitle(R.string.ssl_certificate).setIcon(
3864 R.drawable.ic_dialog_browser_certificate_partially_secure)
3865 .setView(certificateView)
3866 .setPositiveButton(R.string.ok,
3867 new DialogInterface.OnClickListener() {
3868 public void onClick(DialogInterface dialog,
3869 int whichButton) {
3870 mSSLCertificateOnErrorDialog = null;
3871 mSSLCertificateOnErrorView = null;
3872 mSSLCertificateOnErrorHandler = null;
3873 mSSLCertificateOnErrorError = null;
3874
3875 mWebViewClient.onReceivedSslError(
3876 view, handler, error);
3877 }
3878 })
3879 .setNeutralButton(R.string.page_info_view,
3880 new DialogInterface.OnClickListener() {
3881 public void onClick(DialogInterface dialog,
3882 int whichButton) {
3883 mSSLCertificateOnErrorDialog = null;
3884
3885 // do not clear the dialog state: we will
3886 // need to show the dialog again once the
3887 // user is done exploring the page-info details
3888
The Android Open Source Projected217d92008-12-17 18:05:52 -08003889 showPageInfo(mTabControl.getTabFromView(view),
3890 true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003891 }
3892 })
3893 .setOnCancelListener(
3894 new DialogInterface.OnCancelListener() {
3895 public void onCancel(DialogInterface dialog) {
3896 mSSLCertificateOnErrorDialog = null;
3897 mSSLCertificateOnErrorView = null;
3898 mSSLCertificateOnErrorHandler = null;
3899 mSSLCertificateOnErrorError = null;
3900
3901 mWebViewClient.onReceivedSslError(
3902 view, handler, error);
3903 }
3904 })
3905 .show();
3906 }
3907
3908 /**
3909 * Inflates the SSL certificate view (helper method).
3910 * @param certificate The SSL certificate.
3911 * @return The resultant certificate view with issued-to, issued-by,
3912 * issued-on, expires-on, and possibly other fields set.
3913 * If the input certificate is null, returns null.
3914 */
3915 private View inflateCertificateView(SslCertificate certificate) {
3916 if (certificate == null) {
3917 return null;
3918 }
3919
3920 LayoutInflater factory = LayoutInflater.from(this);
3921
3922 View certificateView = factory.inflate(
3923 R.layout.ssl_certificate, null);
3924
3925 // issued to:
3926 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3927 if (issuedTo != null) {
3928 ((TextView) certificateView.findViewById(R.id.to_common))
3929 .setText(issuedTo.getCName());
3930 ((TextView) certificateView.findViewById(R.id.to_org))
3931 .setText(issuedTo.getOName());
3932 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3933 .setText(issuedTo.getUName());
3934 }
3935
3936 // issued by:
3937 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3938 if (issuedBy != null) {
3939 ((TextView) certificateView.findViewById(R.id.by_common))
3940 .setText(issuedBy.getCName());
3941 ((TextView) certificateView.findViewById(R.id.by_org))
3942 .setText(issuedBy.getOName());
3943 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3944 .setText(issuedBy.getUName());
3945 }
3946
3947 // issued on:
3948 String issuedOn = reformatCertificateDate(
3949 certificate.getValidNotBefore());
3950 ((TextView) certificateView.findViewById(R.id.issued_on))
3951 .setText(issuedOn);
3952
3953 // expires on:
3954 String expiresOn = reformatCertificateDate(
3955 certificate.getValidNotAfter());
3956 ((TextView) certificateView.findViewById(R.id.expires_on))
3957 .setText(expiresOn);
3958
3959 return certificateView;
3960 }
3961
3962 /**
3963 * Re-formats the certificate date (Date.toString()) string to
3964 * a properly localized date string.
3965 * @return Properly localized version of the certificate date string and
3966 * the original certificate date string if fails to localize.
3967 * If the original string is null, returns an empty string "".
3968 */
3969 private String reformatCertificateDate(String certificateDate) {
3970 String reformattedDate = null;
3971
3972 if (certificateDate != null) {
3973 Date date = null;
3974 try {
3975 date = java.text.DateFormat.getInstance().parse(certificateDate);
3976 } catch (ParseException e) {
3977 date = null;
3978 }
3979
3980 if (date != null) {
3981 reformattedDate =
3982 DateFormat.getDateFormat(this).format(date);
3983 }
3984 }
3985
3986 return reformattedDate != null ? reformattedDate :
3987 (certificateDate != null ? certificateDate : "");
3988 }
3989
3990 /**
3991 * Displays an http-authentication dialog.
3992 */
3993 private void showHttpAuthentication(final HttpAuthHandler handler,
3994 final String host, final String realm, final String title,
3995 final String name, final String password, int focusId) {
3996 LayoutInflater factory = LayoutInflater.from(this);
3997 final View v = factory
3998 .inflate(R.layout.http_authentication, null);
3999 if (name != null) {
4000 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4001 }
4002 if (password != null) {
4003 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4004 }
4005
4006 String titleText = title;
4007 if (titleText == null) {
4008 titleText = getText(R.string.sign_in_to).toString().replace(
4009 "%s1", host).replace("%s2", realm);
4010 }
4011
4012 mHttpAuthHandler = handler;
4013 mHttpAuthenticationDialog = new AlertDialog.Builder(this)
4014 .setTitle(titleText)
4015 .setIcon(R.drawable.ic_dialog_alert)
4016 .setView(v)
4017 .setPositiveButton(R.string.action,
4018 new DialogInterface.OnClickListener() {
4019 public void onClick(DialogInterface dialog,
4020 int whichButton) {
4021 String nm = ((EditText) v
4022 .findViewById(R.id.username_edit))
4023 .getText().toString();
4024 String pw = ((EditText) v
4025 .findViewById(R.id.password_edit))
4026 .getText().toString();
4027 BrowserActivity.this.setHttpAuthUsernamePassword
4028 (host, realm, nm, pw);
4029 handler.proceed(nm, pw);
4030 mHttpAuthenticationDialog = null;
4031 mHttpAuthHandler = null;
4032 }})
4033 .setNegativeButton(R.string.cancel,
4034 new DialogInterface.OnClickListener() {
4035 public void onClick(DialogInterface dialog,
4036 int whichButton) {
4037 handler.cancel();
4038 BrowserActivity.this.resetTitleAndRevertLockIcon();
4039 mHttpAuthenticationDialog = null;
4040 mHttpAuthHandler = null;
4041 }})
4042 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4043 public void onCancel(DialogInterface dialog) {
4044 handler.cancel();
4045 BrowserActivity.this.resetTitleAndRevertLockIcon();
4046 mHttpAuthenticationDialog = null;
4047 mHttpAuthHandler = null;
4048 }})
4049 .show();
4050 if (focusId != 0) {
4051 mHttpAuthenticationDialog.findViewById(focusId).requestFocus();
4052 } else {
4053 v.findViewById(R.id.username_edit).requestFocus();
4054 }
4055 }
4056
4057 public int getProgress() {
4058 return mWebView.getProgress();
4059 }
4060
4061 /**
4062 * Set HTTP authentication password.
4063 *
4064 * @param host The host for the password
4065 * @param realm The realm for the password
4066 * @param username The username for the password. If it is null, it means
4067 * password can't be saved.
4068 * @param password The password
4069 */
4070 public void setHttpAuthUsernamePassword(String host, String realm,
4071 String username,
4072 String password) {
4073 mWebView.setHttpAuthUsernamePassword(host, realm, username, password);
4074 }
4075
4076 /**
4077 * http stack says net has come or gone... inform the user
4078 * @param up true if net has come up, false if net has gone down
4079 */
4080 public void onNetworkToggle(boolean up) {
4081 if (up) {
4082 if (mAlertDialog != null) {
4083 mAlertDialog.cancel();
4084 mAlertDialog = null;
4085 }
4086 } else {
4087 if (mInLoad && mAlertDialog == null) {
4088 mAlertDialog = new AlertDialog.Builder(this)
4089 .setTitle(R.string.loadSuspendedTitle)
4090 .setMessage(R.string.loadSuspended)
4091 .setPositiveButton(R.string.ok, null)
4092 .show();
4093 }
4094 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08004095 mTabControl.getCurrentWebView().setNetworkAvailable(up);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004096 }
4097
4098 @Override
4099 protected void onActivityResult(int requestCode, int resultCode,
4100 Intent intent) {
4101 switch (requestCode) {
4102 case BOOKMARKS_PAGE:
4103 case CLASSIC_HISTORY_PAGE:
4104 if (resultCode == RESULT_OK && intent != null) {
4105 String data = intent.getAction();
4106 Bundle extras = intent.getExtras();
4107 if (extras != null && extras.getBoolean("new_window", false)) {
4108 openTab(data);
4109 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004110 final TabControl.Tab currentTab =
4111 mTabControl.getCurrentTab();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004112 // If the Window overview is up and we are not in the
4113 // middle of an animation, animate away from it to the
4114 // current tab.
4115 if (mTabOverview != null && mAnimationCount == 0) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004116 sendAnimateFromOverview(currentTab, false, data,
4117 TAB_OVERVIEW_DELAY, null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004118 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004119 dismissSubWindow(currentTab);
4120 if (data != null && data.length() != 0) {
4121 getTopWindow().loadUrl(data);
4122 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004123 }
4124 }
4125 }
4126 break;
4127 default:
4128 break;
4129 }
4130 getTopWindow().requestFocus();
4131 }
4132
4133 /*
4134 * This method is called as a result of the user selecting the options
4135 * menu to see the download window, or when a download changes state. It
4136 * shows the download window ontop of the current window.
4137 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08004138 /* package */ void viewDownloads(Uri downloadRecord) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004139 Intent intent = new Intent(this,
4140 BrowserDownloadPage.class);
4141 intent.setData(downloadRecord);
4142 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4143
4144 }
4145
4146 /**
4147 * Handle results from Tab Switcher mTabOverview tool
4148 */
4149 private class TabListener implements ImageGrid.Listener {
4150 public void remove(int position) {
4151 // Note: Remove is not enabled if we have only one tab.
4152 if (Config.DEBUG && mTabControl.getTabCount() == 1) {
4153 throw new AssertionError();
4154 }
4155
The Android Open Source Projected217d92008-12-17 18:05:52 -08004156 // Remember the current tab.
4157 TabControl.Tab current = mTabControl.getCurrentTab();
4158 final TabControl.Tab remove = mTabControl.getTab(position);
4159 mTabControl.removeTab(remove);
4160 // If we removed the current tab, use the tab at position - 1 if
4161 // possible.
4162 if (current == remove) {
4163 // If the user removes the last tab, act like the New Tab item
4164 // was clicked on.
4165 if (mTabControl.getTabCount() == 0) {
4166 current = mTabControl.createNewTab(false);
4167 sendAnimateFromOverview(current, true,
4168 mSettings.getHomePage(), TAB_OVERVIEW_DELAY, null);
4169 } else {
4170 final int index = position > 0 ? (position - 1) : 0;
4171 current = mTabControl.getTab(index);
4172 }
4173 }
4174
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004175 // The tab overview could have been dismissed before this method is
4176 // called.
4177 if (mTabOverview != null) {
4178 // Remove the tab and change the index.
The Android Open Source Projected217d92008-12-17 18:05:52 -08004179 mTabOverview.remove(position);
4180 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004181 }
4182
4183 // FIXME: This isn't really right. We don't have a current WebView
4184 // since we are switching between tabs and haven't selected a new
4185 // one. This just prevents a NPE in case the user hits home from the
4186 // tab switcher.
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004187 // Only the current tab ensures its WebView is non-null. This
4188 // implies that we are reloading the freed tab.
The Android Open Source Projected217d92008-12-17 18:05:52 -08004189 mTabControl.setCurrentTab(current);
4190 mWebView = current.getWebView();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004191 }
4192 public void onClick(int index) {
4193 // Change the tab if necessary.
4194 // Index equals ImageGrid.CANCEL when pressing back from the tab
4195 // overview.
4196 if (index == ImageGrid.CANCEL) {
4197 index = mTabControl.getCurrentIndex();
4198 // The current index is -1 if the current tab was removed.
4199 if (index == -1) {
4200 // Take the last tab as a fallback.
4201 index = mTabControl.getTabCount() - 1;
4202 }
4203 }
4204
4205 // Clear all the data for tab picker so next time it will be
4206 // recreated.
4207 mTabControl.wipeAllPickerData();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004208
4209 // NEW_TAB means that the "New Tab" cell was clicked on.
4210 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004211 openTabAndShow(mSettings.getHomePage(), null, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004212 } else {
4213 sendAnimateFromOverview(mTabControl.getTab(index),
4214 false, null, 0, null);
4215 }
4216 }
4217 }
4218
4219 // A fake View that draws the WebView's picture with a fast zoom filter.
4220 // The View is used in case the tab is freed during the animation because
4221 // of low memory.
4222 private static class AnimatingView extends View {
4223 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4224 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4225 private static final DrawFilter sZoomFilter =
4226 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4227 private final Picture mPicture;
4228 private final float mScale;
4229 private final int mScrollX;
4230 private final int mScrollY;
4231 final TabControl.Tab mTab;
4232
4233 AnimatingView(Context ctxt, TabControl.Tab t) {
4234 super(ctxt);
4235 mTab = t;
4236 // Use the top window in the animation since the tab overview will
4237 // display the top window in each cell.
4238 final WebView w = t.getTopWindow();
4239 mPicture = w.capturePicture();
4240 mScale = w.getScale() / w.getWidth();
4241 mScrollX = w.getScrollX();
4242 mScrollY = w.getScrollY();
4243 }
4244
4245 @Override
4246 protected void onDraw(Canvas canvas) {
4247 canvas.save();
4248 canvas.drawColor(Color.WHITE);
The Android Open Source Projected217d92008-12-17 18:05:52 -08004249 if (mPicture != null) {
4250 canvas.setDrawFilter(sZoomFilter);
4251 float scale = getWidth() * mScale;
4252 canvas.scale(scale, scale);
4253 canvas.translate(-mScrollX, -mScrollY);
4254 canvas.drawPicture(mPicture);
4255 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004256 canvas.restore();
4257 }
4258 }
4259
4260 /**
4261 * Open the tab picker. This function will always use the current tab in
4262 * its animation.
4263 * @param stay boolean stating whether the tab picker is to remain open
4264 * (in which case it needs a listener and its menu) or not.
4265 * @param index The index of the tab to show as the selection in the tab
4266 * overview.
4267 * @param remove If true, the tab at index will be removed after the
4268 * animation completes.
4269 */
4270 private void tabPicker(final boolean stay, final int index,
4271 final boolean remove) {
4272 if (mTabOverview != null) {
4273 return;
4274 }
4275
4276 int size = mTabControl.getTabCount();
4277
4278 TabListener l = null;
4279 if (stay) {
4280 l = mTabListener = new TabListener();
4281 }
4282 mTabOverview = new ImageGrid(this, stay, l);
4283
4284 for (int i = 0; i < size; i++) {
4285 final TabControl.Tab t = mTabControl.getTab(i);
4286 mTabControl.populatePickerData(t);
4287 mTabOverview.add(t);
4288 }
4289
4290 // Tell the tab overview to show the current tab, the tab overview will
4291 // handle the "New Tab" case.
4292 int currentIndex = mTabControl.getCurrentIndex();
4293 mTabOverview.setCurrentIndex(currentIndex);
4294
4295 // Attach the tab overview.
4296 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4297
4298 // Create a fake AnimatingView to animate the WebView's picture.
4299 final TabControl.Tab current = mTabControl.getCurrentTab();
4300 final AnimatingView v = new AnimatingView(this, current);
4301 mContentView.addView(v, COVER_SCREEN_PARAMS);
4302 removeTabFromContentView(current);
4303 // Pause timers to get the animation smoother.
4304 current.getWebView().pauseTimers();
4305
4306 // Send a message so the tab picker has a chance to layout and get
4307 // positions for all the cells.
4308 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4309 index, remove ? 1 : 0, v));
4310 // Setting this will indicate that we are animating to the overview. We
4311 // set it here to prevent another request to animate from coming in
4312 // between now and when ANIMATE_TO_OVERVIEW is handled.
4313 mAnimationCount++;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004314 // Always change the title bar to the window overview title while
4315 // animating.
4316 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4317 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4318 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4319 Window.PROGRESS_VISIBILITY_OFF);
4320 setTitle(R.string.tab_picker_title);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004321 // Make the menu empty until the animation completes.
4322 mMenuState = EMPTY_MENU;
4323 }
4324
4325 private void bookmarksPicker() {
4326 Intent intent = new Intent(this,
4327 BrowserBookmarksPage.class);
4328 String title = mWebView.getTitle();
4329 String url = mWebView.getUrl();
4330 // Just in case the user opens bookmarks before a page finishes loading
4331 // so the current history item, and therefore the page, is null.
4332 if (null == url) {
4333 url = mLastEnteredUrl;
4334 // This can happen.
4335 if (null == url) {
4336 url = mSettings.getHomePage();
4337 }
4338 }
4339 // In case the web page has not yet received its associated title.
4340 if (title == null) {
4341 title = url;
4342 }
4343 intent.putExtra("title", title);
4344 intent.putExtra("url", url);
4345 intent.putExtra("maxTabsOpen",
4346 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4347 startActivityForResult(intent, BOOKMARKS_PAGE);
4348 }
4349
The Android Open Source Projected217d92008-12-17 18:05:52 -08004350 // Called when loading from context menu or LOAD_URL message
4351 private void loadURL(WebView view, String url) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004352 // In case the user enters nothing.
The Android Open Source Projected217d92008-12-17 18:05:52 -08004353 if (url != null && url.length() != 0 && view != null) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004354 url = smartUrlFilter(url);
The Android Open Source Projected217d92008-12-17 18:05:52 -08004355 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4356 view.loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004357 }
4358 }
4359 }
4360
4361 private void checkMemory() {
4362 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4363 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4364 .getMemoryInfo(mi);
4365 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4366 // mi.threshold) for now
4367 // if (mi.lowMemory) {
4368 if (mi.availMem < mi.threshold) {
4369 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4370 + (mi.availMem / 1024) + "K threshold="
4371 + (mi.threshold / 1024) + "K");
4372 mTabControl.freeMemory();
4373 }
4374 }
4375
4376 private String smartUrlFilter(Uri inUri) {
4377 if (inUri != null) {
4378 return smartUrlFilter(inUri.toString());
4379 }
4380 return null;
4381 }
4382
4383
4384 // get window count
4385
4386 int getWindowCount(){
4387 if(mTabControl != null){
4388 return mTabControl.getTabCount();
4389 }
4390 return 0;
4391 }
4392
4393 static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4394 "(?i)" + // switch on case insensitive matching
4395 "(" + // begin group for schema
4396 "(?:http|https|file):\\/\\/" +
4397 "|(?:data|about|content|javascript):" +
4398 ")" +
4399 "(.*)" );
4400
4401 /**
4402 * Attempts to determine whether user input is a URL or search
4403 * terms. Anything with a space is passed to search.
4404 *
4405 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4406 * "Http://" converts to "http://"
4407 *
4408 * @return Original or modified URL
4409 *
4410 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08004411 String smartUrlFilter(String url) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004412
The Android Open Source Projected217d92008-12-17 18:05:52 -08004413 String inUrl = url.trim();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004414 boolean hasSpace = inUrl.indexOf(' ') != -1;
4415
The Android Open Source Projected217d92008-12-17 18:05:52 -08004416 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4417 if (matcher.matches()) {
4418 if (hasSpace) {
4419 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004420 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08004421 // force scheme to lowercase
4422 String scheme = matcher.group(1);
4423 String lcScheme = scheme.toLowerCase();
4424 if (!lcScheme.equals(scheme)) {
4425 return lcScheme + matcher.group(2);
4426 }
4427 return inUrl;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004428 }
4429 if (hasSpace) {
4430 // FIXME: quick search, need to be customized by setting
4431 if (inUrl.length() > 2 && inUrl.charAt(1) == ' ') {
4432 // FIXME: Is this the correct place to add to searches?
4433 // what if someone else calls this function?
4434 char char0 = inUrl.charAt(0);
4435
4436 if (char0 == 'g') {
4437 Browser.addSearchUrl(mResolver, inUrl);
4438 return composeSearchUrl(inUrl.substring(2));
4439
4440 } else if (char0 == 'w') {
4441 Browser.addSearchUrl(mResolver, inUrl);
4442 return URLUtil.composeSearchUrl(inUrl.substring(2),
4443 QuickSearch_W,
4444 QUERY_PLACE_HOLDER);
4445
4446 } else if (char0 == 'd') {
4447 Browser.addSearchUrl(mResolver, inUrl);
4448 return URLUtil.composeSearchUrl(inUrl.substring(2),
4449 QuickSearch_D,
4450 QUERY_PLACE_HOLDER);
4451
4452 } else if (char0 == 'l') {
4453 Browser.addSearchUrl(mResolver, inUrl);
4454 // FIXME: we need location in this case
4455 return URLUtil.composeSearchUrl(inUrl.substring(2),
4456 QuickSearch_L,
4457 QUERY_PLACE_HOLDER);
4458 }
4459 }
4460 } else {
4461 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4462 return URLUtil.guessUrl(inUrl);
4463 }
4464 }
4465
4466 Browser.addSearchUrl(mResolver, inUrl);
4467 return composeSearchUrl(inUrl);
4468 }
4469
4470 /* package */static String composeSearchUrl(String search) {
4471 return URLUtil.composeSearchUrl(search, QuickSearch_G,
4472 QUERY_PLACE_HOLDER);
4473 }
4474
The Android Open Source Projected217d92008-12-17 18:05:52 -08004475 /* package */void setBaseSearchUrl(String url) {
4476 if (url == null || url.length() == 0) {
4477 /*
4478 * get the google search url based on the SIM. Default is US. NOTE:
4479 * This code uses resources to optionally select the search Uri,
4480 * based on the MCC value from the SIM. The default string will most
4481 * likely be fine. It is parameterized to accept info from the
4482 * Locale, the language code is the first parameter (%1$s) and the
4483 * country code is the second (%2$s). This code must function in the
4484 * same way as a similar lookup in
4485 * com.android.googlesearch.SuggestionProvider#onCreate(). If you
4486 * change either of these functions, change them both. (The same is
4487 * true for the underlying resource strings, which are stored in
4488 * mcc-specific xml files.)
4489 */
4490 Locale l = Locale.getDefault();
4491 QuickSearch_G = getResources().getString(
4492 R.string.google_search_base, l.getLanguage(),
4493 l.getCountry().toLowerCase())
4494 + "client=ms-"
4495 + SystemProperties.get("ro.com.google.clientid", "unknown")
4496 + "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&q=%s";
4497 } else {
4498 QuickSearch_G = url;
4499 }
4500 }
4501
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004502 private final static int LOCK_ICON_UNSECURE = 0;
4503 private final static int LOCK_ICON_SECURE = 1;
4504 private final static int LOCK_ICON_MIXED = 2;
4505
4506 private int mLockIconType = LOCK_ICON_UNSECURE;
4507 private int mPrevLockType = LOCK_ICON_UNSECURE;
4508
4509 private WebView mWebView;
4510 private BrowserSettings mSettings;
4511 private TabControl mTabControl;
4512 private ContentResolver mResolver;
4513 private FrameLayout mContentView;
4514 private ImageGrid mTabOverview;
4515
4516 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4517 // view, we should rewrite this.
4518 private int mCurrentMenuState = 0;
4519 private int mMenuState = R.id.MAIN_MENU;
4520 private static final int EMPTY_MENU = -1;
4521 private Menu mMenu;
4522
4523 private FindDialog mFindDialog;
4524 // Used to prevent chording to result in firing two shortcuts immediately
4525 // one after another. Fixes bug 1211714.
4526 boolean mCanChord;
4527
4528 private boolean mInLoad;
4529
4530 private boolean mPageStarted;
4531 private boolean mActivityInPause = true;
4532
4533 private boolean mMenuIsDown;
4534
4535 private final KeyTracker mKeyTracker = new KeyTracker(this);
4536
4537 // As trackball doesn't send repeat down, we have to track it ourselves
4538 private boolean mTrackTrackball;
4539
4540 private static boolean mInTrace;
4541
4542 // Performance probe
4543 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4544 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4545 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4546 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4547 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4548 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4549 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4550 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4551 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4552 };
4553
4554 private long mStart;
4555 private long mProcessStart;
4556 private long mUserStart;
4557 private long mSystemStart;
4558 private long mIdleStart;
4559 private long mIrqStart;
4560
4561 private long mUiStart;
4562
4563 private Drawable mMixLockIcon;
4564 private Drawable mSecLockIcon;
4565 private Drawable mGenericFavicon;
4566
4567 /* hold a ref so we can auto-cancel if necessary */
4568 private AlertDialog mAlertDialog;
4569
4570 // Wait for credentials before loading google.com
4571 private ProgressDialog mCredsDlg;
4572
4573 // The up-to-date URL and title (these can be different from those stored
4574 // in WebView, since it takes some time for the information in WebView to
4575 // get updated)
4576 private String mUrl;
4577 private String mTitle;
4578
4579 // As PageInfo has different style for landscape / portrait, we have
4580 // to re-open it when configuration changed
4581 private AlertDialog mPageInfoDialog;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004582 private TabControl.Tab mPageInfoView;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004583 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4584 // dialog, we should not just dismiss it, but should get back to the
4585 // SSL-certificate-on-error dialog. This flag is used to store this state
4586 private Boolean mPageInfoFromShowSSLCertificateOnError;
4587
4588 // as SSLCertificateOnError has different style for landscape / portrait,
4589 // we have to re-open it when configuration changed
4590 private AlertDialog mSSLCertificateOnErrorDialog;
4591 private WebView mSSLCertificateOnErrorView;
4592 private SslErrorHandler mSSLCertificateOnErrorHandler;
4593 private SslError mSSLCertificateOnErrorError;
4594
4595 // as SSLCertificate has different style for landscape / portrait, we
4596 // have to re-open it when configuration changed
4597 private AlertDialog mSSLCertificateDialog;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004598 private TabControl.Tab mSSLCertificateView;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004599
4600 // as HttpAuthentication has different style for landscape / portrait, we
4601 // have to re-open it when configuration changed
4602 private AlertDialog mHttpAuthenticationDialog;
4603 private HttpAuthHandler mHttpAuthHandler;
4604
4605 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4606 new FrameLayout.LayoutParams(
4607 ViewGroup.LayoutParams.FILL_PARENT,
4608 ViewGroup.LayoutParams.FILL_PARENT);
4609 // We may provide UI to customize these
4610 // Google search from the browser
The Android Open Source Projected217d92008-12-17 18:05:52 -08004611 static String QuickSearch_G;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004612 // Wikipedia search
4613 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4614 // Dictionary search
4615 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4616 // Google Mobile Local search
4617 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4618
The Android Open Source Projected217d92008-12-17 18:05:52 -08004619 final static String QUERY_PLACE_HOLDER = "%s";
4620
4621 // "source" parameter for Google search through search key
4622 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4623 // "source" parameter for Google search through search menu
4624 final static String GOOGLE_SEARCH_SOURCE_SEARCHMENU = "browser-menu";
4625 // "source" parameter for Google search through goto menu
4626 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4627 // "source" parameter for Google search through simplily type
4628 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4629 // "source" parameter for Google search suggested by the browser
4630 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4631 // "source" parameter for Google search from unknown source
4632 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004633
4634 private final static String LOGTAG = "browser";
4635
4636 private TabListener mTabListener;
4637
4638 private String mLastEnteredUrl;
4639
4640 private PowerManager.WakeLock mWakeLock;
4641 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4642
4643 private Toast mStopToast;
4644
4645 // Used during animations to prevent other animations from being triggered.
4646 // A count is used since the animation to and from the Window overview can
4647 // overlap. A count of 0 means no animation where a count of > 0 means
4648 // there are animations in progress.
4649 private int mAnimationCount;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004650
4651 // As the ids are dynamically created, we can't guarantee that they will
4652 // be in sequence, so this static array maps ids to a window number.
4653 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4654 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4655 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4656 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004657
4658 // monitor platform changes
4659 private IntentFilter mNetworkStateChangedFilter;
4660 private BroadcastReceiver mNetworkStateIntentReceiver;
4661
4662 // activity requestCode
4663 final static int BOOKMARKS_PAGE = 1;
4664 final static int CLASSIC_HISTORY_PAGE = 2;
4665 final static int DOWNLOAD_PAGE = 3;
4666 final static int PREFERENCES_PAGE = 4;
4667
4668 // the frenquency of checking whether system memory is low
4669 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
4670}