blob: 7c6fa04588d7381f390bd2652805dd2e89f23464 [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.
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800582 if (mTabControl.getCurrentWebView() != null) {
583 mTabControl.getCurrentWebView().refreshPlugins(false);
584 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700585 } catch (IOException e) {
586 Log.e(TAG, "IO Exception: " + e);
587 }
588 }
589 };
590
591 /**
592 * Copy the content of assets/plugins/ to the app_plugins directory
593 * in the data partition.
594 *
595 * This function is called every time the browser is started.
596 * We first check if the system image is newer than the one that
597 * copied the plugins (if there's plugins in the data partition).
598 * If this is the case, we then check if the versions are different.
599 * If they are different, we clean the plugins directory in the
600 * data partition, then start a thread to copy the plugins while
601 * the browser continue to load.
602 *
603 * @param overwrite if true overwrite the files even if they are
604 * already present (to let the user "reset" the plugins if needed).
605 */
606 private void copyPlugins(boolean overwrite) {
607 CopyPlugins copyPluginsFromAssets = new CopyPlugins(overwrite, this);
608 copyPluginsFromAssets.initPluginsPath();
609 if (copyPluginsFromAssets.newSystemImage()) {
610 if (copyPluginsFromAssets.checkIsDifferentVersions()) {
611 copyPluginsFromAssets.cleanPluginsDirectory();
The Android Open Source Projected217d92008-12-17 18:05:52 -0800612 Thread copyplugins = new Thread(copyPluginsFromAssets);
613 copyplugins.setName("CopyPlugins");
614 copyplugins.start();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700615 }
616 }
617 }
618
The Android Open Source Projected217d92008-12-17 18:05:52 -0800619 private class ClearThumbnails extends AsyncTask<File, Void, Void> {
620 @Override
621 public Void doInBackground(File... files) {
622 if (files != null) {
623 for (File f : files) {
624 f.delete();
625 }
626 }
627 return null;
628 }
629 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700630
631 @Override public void onCreate(Bundle icicle) {
632 if (Config.LOGV) {
633 Log.v(LOGTAG, this + " onStart");
634 }
635 super.onCreate(icicle);
636 this.requestWindowFeature(Window.FEATURE_LEFT_ICON);
637 this.requestWindowFeature(Window.FEATURE_RIGHT_ICON);
638 this.requestWindowFeature(Window.FEATURE_PROGRESS);
639 this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
640
641 // test the browser in OpenGL
642 // requestWindowFeature(Window.FEATURE_OPENGL);
643
644 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
645
646 mResolver = getContentResolver();
647
The Android Open Source Projected217d92008-12-17 18:05:52 -0800648 setBaseSearchUrl(PreferenceManager.getDefaultSharedPreferences(this)
649 .getString("search_url", ""));
650
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700651 //
652 // start MASF proxy service
653 //
654 //Intent proxyServiceIntent = new Intent();
655 //proxyServiceIntent.setComponent
656 // (new ComponentName(
657 // "com.android.masfproxyservice",
658 // "com.android.masfproxyservice.MasfProxyService"));
659 //startService(proxyServiceIntent, null);
660
661 mSecLockIcon = Resources.getSystem().getDrawable(
662 android.R.drawable.ic_secure);
663 mMixLockIcon = Resources.getSystem().getDrawable(
664 android.R.drawable.ic_partial_secure);
665 mGenericFavicon = getResources().getDrawable(
666 R.drawable.app_web_browser_sm);
667
668
669 mContentView = new FrameLayout(this);
670
671 setContentView(mContentView);
672
673 // Create the tab control and our initial tab
674 mTabControl = new TabControl(this);
675
676 // Open the icon database and retain all the bookmark urls for favicons
677 retainIconsOnStartup();
678
679 // Keep a settings instance handy.
680 mSettings = BrowserSettings.getInstance();
681 mSettings.setTabControl(mTabControl);
682 mSettings.loadFromDb(this);
683
684 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
685 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
686
687 if (!mTabControl.restoreState(icicle)) {
The Android Open Source Projected217d92008-12-17 18:05:52 -0800688 // clear up the thumbnail directory if we can't restore the state as
689 // none of the files in the directory are referenced any more.
690 new ClearThumbnails().execute(
691 mTabControl.getThumbnailDir().listFiles());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700692 final Intent intent = getIntent();
693 final Bundle extra = intent.getExtras();
694 // Create an initial tab.
The Android Open Source Projected217d92008-12-17 18:05:52 -0800695 // If the intent is ACTION_VIEW and data is not null, the Browser is
696 // invoked to view the content by another application. In this case,
697 // the tab will be close when exit.
698 final TabControl.Tab t = mTabControl.createNewTab(
699 Intent.ACTION_VIEW.equals(intent.getAction()) &&
700 intent.getData() != null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700701 mTabControl.setCurrentTab(t);
702 // This is one of the only places we call attachTabToContentView
703 // without animating from the tab picker.
704 attachTabToContentView(t);
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800705 WebView webView = t.getWebView();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700706 if (extra != null) {
707 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
708 if (scale > 0 && scale <= 1000) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800709 webView.setInitialScale(scale);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700710 }
711 }
712 // If we are not restoring from an icicle, then there is a high
713 // likely hood this is the first run. So, check to see if the
714 // homepage needs to be configured and copy any plugins from our
715 // asset directory to the data partition.
716 if ((extra == null || !extra.getBoolean("testing"))
717 && !mSettings.isLoginInitialized()) {
718 setupHomePage();
719 }
720 copyPlugins(true);
721
722 String url = getUrlFromIntent(intent);
723 if (url == null || url.length() == 0) {
724 if (mSettings.isLoginInitialized()) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800725 webView.loadUrl(mSettings.getHomePage());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700726 } else {
727 waitForCredentials();
728 }
729 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800730 webView.loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700731 }
732 } else {
733 // TabControl.restoreState() will create a new tab even if
734 // restoring the state fails. Attach it to the view here since we
735 // are not animating from the tab picker.
736 attachTabToContentView(mTabControl.getCurrentTab());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700737 }
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 Project765e7c92009-01-09 17:51:25 -0800760 TabControl.Tab current = mTabControl.getCurrentTab();
The Android Open Source Projected217d92008-12-17 18:05:52 -0800761 // When a tab is closed on exit, the current tab index is set to -1.
762 // Reset before proceed as Browser requires the current tab to be set.
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800763 if (current == null) {
764 // Try to reset the tab in case the index was incorrect.
765 current = mTabControl.getTab(0);
766 if (current == null) {
767 // No tabs at all so just ignore this intent.
768 return;
769 }
The Android Open Source Projected217d92008-12-17 18:05:52 -0800770 mTabControl.setCurrentTab(current);
771 attachTabToContentView(current);
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800772 resetTitleAndIcon(current.getWebView());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700773 }
774 final String action = intent.getAction();
775 final int flags = intent.getFlags();
776 if (Intent.ACTION_MAIN.equals(action) ||
777 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
778 // just resume the browser
779 return;
780 }
781 if (Intent.ACTION_VIEW.equals(action)
782 || Intent.ACTION_SEARCH.equals(action)
The Android Open Source Projected217d92008-12-17 18:05:52 -0800783 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700784 || Intent.ACTION_WEB_SEARCH.equals(action)) {
785 String url = getUrlFromIntent(intent);
786 if (url == null || url.length() == 0) {
787 url = mSettings.getHomePage();
788 }
789 if (Intent.ACTION_VIEW.equals(action) &&
790 (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
791 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url will be
The Android Open Source Projected217d92008-12-17 18:05:52 -0800792 // opened in a new tab unless we have reached MAX_TABS. Then the
793 // url will be opened in the current tab. If a new tab is
794 // created, it will have "true" for exit on close.
795 openTabAndShow(url, null, true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700796 } else {
797 if ("about:debug".equals(url)) {
798 mSettings.toggleDebugSettings();
799 return;
800 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700801 // If the Window overview is up and we are not in the midst of
802 // an animation, animate away from the Window overview.
803 if (mTabOverview != null && mAnimationCount == 0) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800804 sendAnimateFromOverview(current, false, url,
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700805 TAB_OVERVIEW_DELAY, null);
806 } else {
807 // Get rid of the subwindow if it exists
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800808 dismissSubWindow(current);
809 current.getWebView().loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700810 }
811 }
812 }
813 }
814
815 private String getUrlFromIntent(Intent intent) {
816 String url = null;
817 if (intent != null) {
818 final String action = intent.getAction();
819 if (Intent.ACTION_VIEW.equals(action)) {
820 url = smartUrlFilter(intent.getData());
821 if (url != null && url.startsWith("content:")) {
822 /* Append mimetype so webview knows how to display */
823 String mimeType = intent.resolveType(getContentResolver());
824 if (mimeType != null) {
825 url += "?" + mimeType;
826 }
827 }
828 } else if (Intent.ACTION_SEARCH.equals(action)
The Android Open Source Projected217d92008-12-17 18:05:52 -0800829 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700830 || Intent.ACTION_WEB_SEARCH.equals(action)) {
831 url = intent.getStringExtra(SearchManager.QUERY);
The Android Open Source Projected217d92008-12-17 18:05:52 -0800832 if (url != null) {
833 mLastEnteredUrl = url;
834 // Don't add Urls, just search terms.
835 // Urls will get added when the page is loaded.
836 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
837 Browser.updateVisitedHistory(mResolver, url, false);
838 }
839 // In general, we shouldn't modify URL from Intent.
840 // But currently, we get the user-typed URL from search box as well.
841 url = fixUrl(url);
842 url = smartUrlFilter(url);
843 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
844 if (url.contains(searchSource)) {
845 String source = null;
846 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
847 if (appData != null) {
848 source = appData.getString(SearchManager.SOURCE);
849 }
850 if (TextUtils.isEmpty(source)) {
851 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
852 }
853 url = url.replace(searchSource, "&source=android-"+source+"&");
854 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700855 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700856 }
857 }
858 return url;
859 }
860
The Android Open Source Projected217d92008-12-17 18:05:52 -0800861 /* package */ static String fixUrl(String inUrl) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700862 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
863 return inUrl;
864 if (inUrl.startsWith("http:") ||
865 inUrl.startsWith("https:")) {
866 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
867 inUrl = inUrl.replaceFirst("/", "//");
868 } else inUrl = inUrl.replaceFirst(":", "://");
869 }
870 return inUrl;
871 }
872
873 /**
874 * Looking for the pattern like this
875 *
876 * *
877 * * *
878 * *** * *******
879 * * *
880 * * *
881 * *
882 */
883 private final SensorListener mSensorListener = new SensorListener() {
884 private long mLastGestureTime;
885 private float[] mPrev = new float[3];
886 private float[] mPrevDiff = new float[3];
887 private float[] mDiff = new float[3];
888 private float[] mRevertDiff = new float[3];
889
890 public void onSensorChanged(int sensor, float[] values) {
891 boolean show = false;
892 float[] diff = new float[3];
893
894 for (int i = 0; i < 3; i++) {
895 diff[i] = values[i] - mPrev[i];
896 if (Math.abs(diff[i]) > 1) {
897 show = true;
898 }
899 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
900 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
901 // start track when there is a big move, or revert
902 mRevertDiff[i] = mDiff[i];
903 mDiff[i] = 0;
904 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
905 // reset when it is flat
906 mDiff[i] = mRevertDiff[i] = 0;
907 }
908 mDiff[i] += diff[i];
909 mPrevDiff[i] = diff[i];
910 mPrev[i] = values[i];
911 }
912
913 if (false) {
914 // only shows if we think the delta is big enough, in an attempt
915 // to detect "serious" moves left/right or up/down
916 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
917 + values[0] + ", " + values[1] + ", " + values[2] + ")"
918 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
919 + ")");
920 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
921 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
922 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
923 + mRevertDiff[2] + ")");
924 }
925
926 long now = android.os.SystemClock.uptimeMillis();
927 if (now - mLastGestureTime > 1000) {
928 mLastGestureTime = 0;
929
930 float y = mDiff[1];
931 float z = mDiff[2];
932 float ay = Math.abs(y);
933 float az = Math.abs(z);
934 float ry = mRevertDiff[1];
935 float rz = mRevertDiff[2];
936 float ary = Math.abs(ry);
937 float arz = Math.abs(rz);
938 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
939 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
940
941 if ((gestY || gestZ) && !(gestY && gestZ)) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800942 WebView view = mTabControl.getCurrentWebView();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700943
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800944 if (view != null) {
945 if (gestZ) {
946 if (z < 0) {
947 view.zoomOut();
948 } else {
949 view.zoomIn();
950 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700951 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800952 view.flingScroll(0, Math.round(y * 100));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700953 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700954 }
955 mLastGestureTime = now;
956 }
957 }
958 }
959
960 public void onAccuracyChanged(int sensor, int accuracy) {
961 // TODO Auto-generated method stub
962
963 }
964 };
965
966 @Override protected void onResume() {
967 super.onResume();
968 if (Config.LOGV) {
969 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
970 }
971
972 if (!mActivityInPause) {
973 Log.e(LOGTAG, "BrowserActivity is already resumed.");
974 return;
975 }
976
977 mActivityInPause = false;
978 resumeWebView();
979
980 if (mWakeLock.isHeld()) {
981 mHandler.removeMessages(RELEASE_WAKELOCK);
982 mWakeLock.release();
983 }
984
985 if (mCredsDlg != null) {
986 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
987 // In case credential request never comes back
988 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
989 }
990 }
991
992 registerReceiver(mNetworkStateIntentReceiver,
993 mNetworkStateChangedFilter);
994 WebView.enablePlatformNotifications();
995
996 if (mSettings.doFlick()) {
997 if (mSensorManager == null) {
998 mSensorManager = (SensorManager) getSystemService(
999 Context.SENSOR_SERVICE);
1000 }
1001 mSensorManager.registerListener(mSensorListener,
1002 SensorManager.SENSOR_ACCELEROMETER,
1003 SensorManager.SENSOR_DELAY_FASTEST);
1004 } else {
1005 mSensorManager = null;
1006 }
1007 }
1008
1009 /**
1010 * onSaveInstanceState(Bundle map)
1011 * onSaveInstanceState is called right before onStop(). The map contains
1012 * the saved state.
1013 */
1014 @Override protected void onSaveInstanceState(Bundle outState) {
1015 if (Config.LOGV) {
1016 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1017 }
1018 // the default implementation requires each view to have an id. As the
1019 // browser handles the state itself and it doesn't use id for the views,
1020 // don't call the default implementation. Otherwise it will trigger the
1021 // warning like this, "couldn't save which view has focus because the
1022 // focused view XXX has no id".
1023
1024 // Save all the tabs
1025 mTabControl.saveState(outState);
1026 }
1027
1028 @Override protected void onPause() {
1029 super.onPause();
1030
1031 if (mActivityInPause) {
1032 Log.e(LOGTAG, "BrowserActivity is already paused.");
1033 return;
1034 }
1035
1036 mActivityInPause = true;
The Android Open Source Projected217d92008-12-17 18:05:52 -08001037 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebView()) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001038 mWakeLock.acquire();
1039 mHandler.sendMessageDelayed(mHandler
1040 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1041 }
1042
1043 // Clear the credentials toast if it is up
1044 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1045 mCredsDlg.dismiss();
1046 }
1047 mCredsDlg = null;
1048
1049 cancelStopToast();
1050
1051 // unregister network state listener
1052 unregisterReceiver(mNetworkStateIntentReceiver);
1053 WebView.disablePlatformNotifications();
1054
1055 if (mSensorManager != null) {
1056 mSensorManager.unregisterListener(mSensorListener);
1057 }
1058 }
1059
1060 @Override protected void onDestroy() {
1061 if (Config.LOGV) {
1062 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1063 }
1064 super.onDestroy();
1065 // Remove the current tab and sub window
1066 TabControl.Tab t = mTabControl.getCurrentTab();
1067 dismissSubWindow(t);
1068 removeTabFromContentView(t);
1069 // Destroy all the tabs
1070 mTabControl.destroy();
1071 WebIconDatabase.getInstance().close();
1072 if (mGlsConnection != null) {
1073 unbindService(mGlsConnection);
1074 mGlsConnection = null;
1075 }
1076
1077 //
1078 // stop MASF proxy service
1079 //
1080 //Intent proxyServiceIntent = new Intent();
1081 //proxyServiceIntent.setComponent
1082 // (new ComponentName(
1083 // "com.android.masfproxyservice",
1084 // "com.android.masfproxyservice.MasfProxyService"));
1085 //stopService(proxyServiceIntent);
1086 }
1087
1088 @Override
1089 public void onConfigurationChanged(Configuration newConfig) {
1090 super.onConfigurationChanged(newConfig);
1091
1092 if (mPageInfoDialog != null) {
1093 mPageInfoDialog.dismiss();
1094 showPageInfo(
1095 mPageInfoView,
1096 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1097 }
1098 if (mSSLCertificateDialog != null) {
1099 mSSLCertificateDialog.dismiss();
1100 showSSLCertificate(
1101 mSSLCertificateView);
1102 }
1103 if (mSSLCertificateOnErrorDialog != null) {
1104 mSSLCertificateOnErrorDialog.dismiss();
1105 showSSLCertificateOnError(
1106 mSSLCertificateOnErrorView,
1107 mSSLCertificateOnErrorHandler,
1108 mSSLCertificateOnErrorError);
1109 }
1110 if (mHttpAuthenticationDialog != null) {
1111 String title = ((TextView) mHttpAuthenticationDialog
1112 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1113 .toString();
1114 String name = ((TextView) mHttpAuthenticationDialog
1115 .findViewById(R.id.username_edit)).getText().toString();
1116 String password = ((TextView) mHttpAuthenticationDialog
1117 .findViewById(R.id.password_edit)).getText().toString();
1118 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1119 .getId();
1120 mHttpAuthenticationDialog.dismiss();
1121 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1122 name, password, focusId);
1123 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08001124 if (mFindDialog != null && mFindDialog.isShowing()) {
1125 mFindDialog.onConfigurationChanged(newConfig);
1126 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001127 }
1128
1129 @Override public void onLowMemory() {
1130 super.onLowMemory();
1131 mTabControl.freeMemory();
1132 }
1133
1134 private boolean resumeWebView() {
1135 if ((!mActivityInPause && !mPageStarted) ||
1136 (mActivityInPause && mPageStarted)) {
1137 CookieSyncManager.getInstance().startSync();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001138 WebView w = mTabControl.getCurrentWebView();
1139 if (w != null) {
1140 w.resumeTimers();
1141 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001142 return true;
1143 } else {
1144 return false;
1145 }
1146 }
1147
1148 private boolean pauseWebView() {
1149 if (mActivityInPause && !mPageStarted) {
1150 CookieSyncManager.getInstance().stopSync();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001151 WebView w = mTabControl.getCurrentWebView();
1152 if (w != null) {
1153 w.pauseTimers();
1154 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001155 return true;
1156 } else {
1157 return false;
1158 }
1159 }
1160
1161 /*
1162 * This function is called when we are launching for the first time. We
1163 * are waiting for the login credentials before loading Google home
1164 * pages. This way the user will be logged in straight away.
1165 */
1166 private void waitForCredentials() {
1167 // Show a toast
1168 mCredsDlg = new ProgressDialog(this);
1169 mCredsDlg.setIndeterminate(true);
1170 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1171 // If the user cancels the operation, then cancel the Google
1172 // Credentials request.
1173 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1174 mCredsDlg.show();
1175
1176 // We set a timeout for the retrieval of credentials in onResume()
1177 // as that is when we have freed up some CPU time to get
1178 // the login credentials.
1179 }
1180
1181 /*
1182 * If we have received the credentials or we have timed out and we are
1183 * showing the credentials dialog, then it is time to move on.
1184 */
1185 private void resumeAfterCredentials() {
1186 if (mCredsDlg == null) {
1187 return;
1188 }
1189
1190 // Clear the toast
1191 if (mCredsDlg.isShowing()) {
1192 mCredsDlg.dismiss();
1193 }
1194 mCredsDlg = null;
1195
1196 // Clear any pending timeout
1197 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1198
1199 // Load the page
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001200 WebView w = mTabControl.getCurrentWebView();
1201 if (w != null) {
1202 w.loadUrl(mSettings.getHomePage());
1203 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001204
1205 // Update the settings, need to do this last as it can take a moment
1206 // to persist the settings. In the mean time we could be loading
1207 // content.
1208 mSettings.setLoginInitialized(this);
1209 }
1210
1211 // Open the icon database and retain all the icons for visited sites.
1212 private void retainIconsOnStartup() {
1213 final WebIconDatabase db = WebIconDatabase.getInstance();
1214 db.open(getDir("icons", 0).getPath());
1215 try {
1216 Cursor c = Browser.getAllBookmarks(mResolver);
1217 if (!c.moveToFirst()) {
1218 c.deactivate();
1219 return;
1220 }
1221 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1222 do {
1223 String url = c.getString(urlIndex);
1224 db.retainIconForPageUrl(url);
1225 } while (c.moveToNext());
1226 c.deactivate();
1227 } catch (IllegalStateException e) {
1228 Log.e(LOGTAG, "retainIconsOnStartup", e);
1229 }
1230 }
1231
1232 // Helper method for getting the top window.
1233 WebView getTopWindow() {
1234 return mTabControl.getCurrentTopWebView();
1235 }
1236
1237 @Override
1238 public boolean onCreateOptionsMenu(Menu menu) {
1239 super.onCreateOptionsMenu(menu);
1240
1241 MenuInflater inflater = getMenuInflater();
1242 inflater.inflate(R.menu.browser, menu);
1243 mMenu = menu;
1244 updateInLoadMenuItems();
1245 return true;
1246 }
1247
1248 /**
1249 * As the menu can be open when loading state changes
1250 * we must manually update the state of the stop/reload menu
1251 * item
1252 */
1253 private void updateInLoadMenuItems() {
1254 if (mMenu == null) {
1255 return;
1256 }
1257 MenuItem src = mInLoad ?
1258 mMenu.findItem(R.id.stop_menu_id):
1259 mMenu.findItem(R.id.reload_menu_id);
1260 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1261 dest.setIcon(src.getIcon());
1262 dest.setTitle(src.getTitle());
1263 }
1264
1265 @Override
1266 public boolean onContextItemSelected(MenuItem item) {
1267 // chording is not an issue with context menus, but we use the same
1268 // options selector, so set mCanChord to true so we can access them.
1269 mCanChord = true;
1270 int id = item.getItemId();
The Android Open Source Projected217d92008-12-17 18:05:52 -08001271 final WebView webView = getTopWindow();
1272 final HashMap hrefMap = new HashMap();
1273 hrefMap.put("webview", webView);
1274 final Message msg = mHandler.obtainMessage(
1275 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001276 switch (id) {
1277 // -- Browser context menu
1278 case R.id.open_context_menu_id:
1279 case R.id.open_newtab_context_menu_id:
1280 case R.id.bookmark_context_menu_id:
1281 case R.id.save_link_context_menu_id:
1282 case R.id.share_link_context_menu_id:
1283 case R.id.copy_link_context_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001284 webView.requestFocusNodeHref(msg);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001285 break;
1286
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001287 default:
1288 // For other context menus
1289 return onOptionsItemSelected(item);
1290 }
1291 mCanChord = false;
1292 return true;
1293 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08001294
1295 private Bundle createGoogleSearchSourceBundle(String source) {
1296 Bundle bundle = new Bundle();
1297 bundle.putString(SearchManager.SOURCE, source);
1298 return bundle;
1299 }
1300
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001301 /**
1302 * Overriding this forces the search key to launch global search. The difference
1303 * is the final "true" which requests global search.
1304 */
1305 @Override
1306 public boolean onSearchRequested() {
The Android Open Source Projected217d92008-12-17 18:05:52 -08001307 startSearch(null, false,
1308 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001309 return true;
1310 }
1311
1312 @Override
The Android Open Source Projected217d92008-12-17 18:05:52 -08001313 public void startSearch(String initialQuery, boolean selectInitialQuery,
1314 Bundle appSearchData, boolean globalSearch) {
1315 if (appSearchData == null) {
1316 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1317 }
1318 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1319 }
1320
1321 @Override
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001322 public boolean onOptionsItemSelected(MenuItem item) {
1323 if (!mCanChord) {
1324 // The user has already fired a shortcut with this hold down of the
1325 // menu key.
1326 return false;
1327 }
1328 switch (item.getItemId()) {
1329 // -- Main menu
1330 case R.id.goto_menu_id: {
1331 String url = getTopWindow().getUrl();
The Android Open Source Projected217d92008-12-17 18:05:52 -08001332 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1333 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_GOTO), false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001334 }
1335 break;
The Android Open Source Projected217d92008-12-17 18:05:52 -08001336
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001337 case R.id.search_menu_id:
1338 // launch using "global" search, which will bring up the Google search box
The Android Open Source Projected217d92008-12-17 18:05:52 -08001339 startSearch(null, false,
1340 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHMENU), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001341 break;
The Android Open Source Projected217d92008-12-17 18:05:52 -08001342
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001343 case R.id.bookmarks_menu_id:
1344 bookmarksPicker();
1345 break;
1346
1347 case R.id.windows_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001348 if (mTabControl.getTabCount() == 1) {
1349 openTabAndShow(mSettings.getHomePage(), null, false);
1350 } else {
1351 tabPicker(true, mTabControl.getCurrentIndex(), false);
1352 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001353 break;
1354
1355 case R.id.stop_reload_menu_id:
1356 if (mInLoad) {
1357 stopLoading();
1358 } else {
1359 getTopWindow().reload();
1360 }
1361 break;
1362
1363 case R.id.back_menu_id:
1364 getTopWindow().goBack();
1365 break;
1366
1367 case R.id.forward_menu_id:
1368 getTopWindow().goForward();
1369 break;
1370
1371 case R.id.close_menu_id:
1372 // Close the subwindow if it exists.
1373 if (mTabControl.getCurrentSubWindow() != null) {
1374 dismissSubWindow(mTabControl.getCurrentTab());
1375 break;
1376 }
1377 final int currentIndex = mTabControl.getCurrentIndex();
1378 final TabControl.Tab parent =
1379 mTabControl.getCurrentTab().getParentTab();
1380 int indexToShow = -1;
1381 if (parent != null) {
1382 indexToShow = mTabControl.getTabIndex(parent);
1383 } else {
1384 // Get the last tab in the list. If it is the current tab,
1385 // subtract 1 more.
1386 indexToShow = mTabControl.getTabCount() - 1;
1387 if (currentIndex == indexToShow) {
1388 indexToShow--;
1389 }
1390 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08001391 switchTabs(currentIndex, indexToShow, true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001392 break;
1393
1394 case R.id.homepage_menu_id:
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001395 TabControl.Tab current = mTabControl.getCurrentTab();
1396 if (current != null) {
1397 dismissSubWindow(current);
1398 current.getWebView().loadUrl(mSettings.getHomePage());
1399 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001400 break;
1401
1402 case R.id.preferences_menu_id:
1403 Intent intent = new Intent(this,
1404 BrowserPreferencesPage.class);
1405 startActivityForResult(intent, PREFERENCES_PAGE);
1406 break;
1407
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001408 case R.id.find_menu_id:
1409 if (null == mFindDialog) {
1410 mFindDialog = new FindDialog(this);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001411 }
1412 mFindDialog.setWebView(getTopWindow());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001413 mFindDialog.show();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001414 mMenuState = EMPTY_MENU;
1415 break;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001416
1417 case R.id.page_info_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001418 showPageInfo(mTabControl.getCurrentTab(), false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001419 break;
1420
The Android Open Source Projected217d92008-12-17 18:05:52 -08001421 case R.id.classic_history_menu_id:
1422 loadHistory();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001423 break;
1424
1425 case R.id.bookmark_page_menu_id:
1426 Browser.saveBookmark(this, getTopWindow().getTitle(),
1427 getTopWindow().getUrl());
1428 break;
1429
1430 case R.id.share_page_menu_id:
1431 Browser.sendString(this, getTopWindow().getUrl());
1432 break;
1433
1434 case R.id.dump_nav_menu_id:
1435 getTopWindow().debugDump();
1436 break;
1437
1438 case R.id.zoom_menu_id:
1439 // FIXME: Can we move this out of WebView? How does this work
1440 // for a subwindow?
1441 getTopWindow().invokeZoomPicker();
1442 break;
1443
1444 case R.id.zoom_in_menu_id:
1445 getTopWindow().zoomIn();
1446 break;
1447
1448 case R.id.zoom_out_menu_id:
1449 getTopWindow().zoomOut();
1450 break;
1451
1452 case R.id.view_downloads_menu_id:
1453 viewDownloads(null);
1454 break;
1455
1456 case R.id.flip_orientation_menu_id:
1457 if (mSettings.getOrientation() !=
1458 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001459 mSettings.setOrientation(this,
1460 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001461 } else {
1462 mSettings.setOrientation(this,
1463 ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
1464 }
1465 setRequestedOrientation(mSettings.getOrientation());
1466 break;
1467
1468 // -- Tab menu
1469 case R.id.view_tab_menu_id:
1470 if (mTabListener != null && mTabOverview != null) {
1471 int pos = mTabOverview.getContextMenuPosition(item);
1472 mTabOverview.setCurrentIndex(pos);
1473 mTabListener.onClick(pos);
1474 }
1475 break;
1476
1477 case R.id.remove_tab_menu_id:
1478 if (mTabListener != null && mTabOverview != null) {
1479 int pos = mTabOverview.getContextMenuPosition(item);
1480 mTabListener.remove(pos);
1481 }
1482 break;
1483
1484 case R.id.new_tab_menu_id:
1485 // No need to check for mTabOverview here since we are not
1486 // dependent on it for a position.
1487 if (mTabListener != null) {
1488 // If the overview happens to be non-null, make the "New
1489 // Tab" cell visible.
1490 if (mTabOverview != null) {
1491 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1492 }
1493 mTabListener.onClick(ImageGrid.NEW_TAB);
1494 }
1495 break;
1496
1497 case R.id.bookmark_tab_menu_id:
1498 if (mTabListener != null && mTabOverview != null) {
1499 int pos = mTabOverview.getContextMenuPosition(item);
1500 TabControl.Tab t = mTabControl.getTab(pos);
1501 // Since we called populatePickerData for all of the
1502 // tabs, getTitle and getUrl will return appropriate
1503 // values.
1504 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1505 t.getUrl());
1506 }
1507 break;
1508
1509 case R.id.history_tab_menu_id: {
1510 Intent i = new Intent(this, BrowserHistoryPage.class);
1511 i.putExtra("maxTabsOpen",
1512 mTabControl.getTabCount() >=
1513 TabControl.MAX_TABS);
1514 startActivityForResult(i, CLASSIC_HISTORY_PAGE);
1515 }
1516 break;
1517
1518 case R.id.bookmarks_tab_menu_id:
1519 bookmarksPicker();
1520 break;
1521
1522 case R.id.properties_tab_menu_id:
1523 if (mTabListener != null && mTabOverview != null) {
1524 int pos = mTabOverview.getContextMenuPosition(item);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001525 showPageInfo(mTabControl.getTab(pos), false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001526 }
1527 break;
1528
The Android Open Source Projected217d92008-12-17 18:05:52 -08001529 case R.id.window_one_menu_id:
1530 case R.id.window_two_menu_id:
1531 case R.id.window_three_menu_id:
1532 case R.id.window_four_menu_id:
1533 case R.id.window_five_menu_id:
1534 case R.id.window_six_menu_id:
1535 case R.id.window_seven_menu_id:
1536 case R.id.window_eight_menu_id:
1537 {
1538 int menuid = item.getItemId();
1539 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1540 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1541 TabControl.Tab desiredTab = mTabControl.getTab(id);
1542 if (desiredTab != null &&
1543 desiredTab != mTabControl.getCurrentTab()) {
1544 switchTabs(mTabControl.getCurrentIndex(), id, false);
1545 }
1546 break;
1547 }
1548 }
1549 }
1550 break;
1551
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001552 default:
1553 if (!super.onOptionsItemSelected(item)) {
1554 return false;
1555 }
1556 // Otherwise fall through.
1557 }
1558 mCanChord = false;
1559 return true;
1560 }
1561
1562 public void closeFind() {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001563 mMenuState = R.id.MAIN_MENU;
1564 }
1565
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001566 @Override public boolean onPrepareOptionsMenu(Menu menu)
1567 {
1568 // This happens when the user begins to hold down the menu key, so
1569 // allow them to chord to get a shortcut.
1570 mCanChord = true;
1571 // Note: setVisible will decide whether an item is visible; while
1572 // setEnabled() will decide whether an item is enabled, which also means
1573 // whether the matching shortcut key will function.
1574 super.onPrepareOptionsMenu(menu);
1575 switch (mMenuState) {
1576 case R.id.TAB_MENU:
1577 if (mCurrentMenuState != mMenuState) {
1578 menu.setGroupVisible(R.id.MAIN_MENU, false);
1579 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1580 menu.setGroupVisible(R.id.TAB_MENU, true);
1581 menu.setGroupEnabled(R.id.TAB_MENU, true);
1582 }
1583 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1584 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1585 tab.setVisible(newT);
1586 tab.setEnabled(newT);
1587 break;
1588 case EMPTY_MENU:
1589 if (mCurrentMenuState != mMenuState) {
1590 menu.setGroupVisible(R.id.MAIN_MENU, false);
1591 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1592 menu.setGroupVisible(R.id.TAB_MENU, false);
1593 menu.setGroupEnabled(R.id.TAB_MENU, false);
1594 }
1595 break;
1596 default:
1597 if (mCurrentMenuState != mMenuState) {
1598 menu.setGroupVisible(R.id.MAIN_MENU, true);
1599 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1600 menu.setGroupVisible(R.id.TAB_MENU, false);
1601 menu.setGroupEnabled(R.id.TAB_MENU, false);
1602 }
1603 final WebView w = getTopWindow();
1604 boolean canGoBack = w.canGoBack();
1605 final MenuItem back = menu.findItem(R.id.back_menu_id);
1606 back.setVisible(canGoBack);
1607 back.setEnabled(canGoBack);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001608 final MenuItem flip =
1609 menu.findItem(R.id.flip_orientation_menu_id);
1610 boolean keyboardClosed =
The Android Open Source Projected217d92008-12-17 18:05:52 -08001611 getResources().getConfiguration().hardKeyboardHidden ==
1612 Configuration.HARDKEYBOARDHIDDEN_YES;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001613 flip.setEnabled(keyboardClosed);
1614
1615 boolean isHome = mSettings.getHomePage().equals(w.getUrl());
1616 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1617 home.setVisible(!isHome);
1618 home.setEnabled(!isHome);
1619
1620 menu.findItem(R.id.forward_menu_id)
1621 .setEnabled(w.canGoForward());
1622
1623 menu.findItem(R.id.zoom_in_menu_id).setVisible(false);
1624 menu.findItem(R.id.zoom_out_menu_id).setVisible(false);
1625
1626 // decide whether to show the share link option
1627 PackageManager pm = getPackageManager();
1628 Intent send = new Intent(Intent.ACTION_SEND);
1629 send.setType("text/plain");
1630 List<ResolveInfo> list = pm.queryIntentActivities(send,
1631 PackageManager.MATCH_DEFAULT_ONLY);
1632 menu.findItem(R.id.share_page_menu_id).setVisible(
1633 list.size() > 0);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001634
1635 // Hide the menu+<window number> items
1636 // Can't set visibility in menu xml file b/c when a
1637 // group is set visible, all items are set visible.
1638 for (int i = 0; i < WINDOW_SHORTCUT_ID_ARRAY.length; i++) {
1639 menu.findItem(WINDOW_SHORTCUT_ID_ARRAY[i]).setVisible(false);
1640 }
1641
1642 // If there is only 1 window, the text will be "New window"
1643 final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1644 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1645 getString(R.string.view_tabs_condensed) :
1646 getString(R.string.tab_picker_new_tab));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001647
1648 boolean isNavDump = mSettings.isNavDump();
1649 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1650 nav.setVisible(isNavDump);
1651 nav.setEnabled(isNavDump);
1652 break;
1653 }
1654 mCurrentMenuState = mMenuState;
1655 return true;
1656 }
1657
1658 @Override
1659 public void onCreateContextMenu(ContextMenu menu, View v,
1660 ContextMenuInfo menuInfo) {
1661 WebView webview = (WebView) v;
1662 WebView.HitTestResult result = webview.getHitTestResult();
1663 if (result == null) {
1664 return;
1665 }
1666
1667 int type = result.getType();
1668 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1669 Log.w(LOGTAG,
1670 "We should not show context menu when nothing is touched");
1671 return;
1672 }
1673 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1674 // let TextView handles context menu
1675 return;
1676 }
1677
1678 // Note, http://b/issue?id=1106666 is requesting that
1679 // an inflated menu can be used again. This is not available
1680 // yet, so inflate each time (yuk!)
1681 MenuInflater inflater = getMenuInflater();
1682 inflater.inflate(R.menu.browsercontext, menu);
1683
1684 // Show the correct menu group
1685 String extra = result.getExtra();
1686 menu.setGroupVisible(R.id.PHONE_MENU,
1687 type == WebView.HitTestResult.PHONE_TYPE);
1688 menu.setGroupVisible(R.id.EMAIL_MENU,
1689 type == WebView.HitTestResult.EMAIL_TYPE);
1690 menu.setGroupVisible(R.id.GEO_MENU,
1691 type == WebView.HitTestResult.GEO_TYPE);
1692 menu.setGroupVisible(R.id.IMAGE_MENU,
The Android Open Source Projected217d92008-12-17 18:05:52 -08001693 type == WebView.HitTestResult.IMAGE_TYPE
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001694 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1695 menu.setGroupVisible(R.id.ANCHOR_MENU,
The Android Open Source Projected217d92008-12-17 18:05:52 -08001696 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001697 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1698
1699 // Setup custom handling depending on the type
1700 switch (type) {
1701 case WebView.HitTestResult.PHONE_TYPE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001702 menu.setHeaderTitle(Uri.decode(extra));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001703 menu.findItem(R.id.dial_context_menu_id).setIntent(
1704 new Intent(Intent.ACTION_VIEW, Uri
1705 .parse(WebView.SCHEME_TEL + extra)));
The Android Open Source Projected217d92008-12-17 18:05:52 -08001706 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1707 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1708 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001709 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1710 addIntent);
1711 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1712 new Copy(extra));
1713 break;
1714
1715 case WebView.HitTestResult.EMAIL_TYPE:
1716 menu.setHeaderTitle(extra);
1717 menu.findItem(R.id.email_context_menu_id).setIntent(
1718 new Intent(Intent.ACTION_VIEW, Uri
1719 .parse(WebView.SCHEME_MAILTO + extra)));
1720 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1721 new Copy(extra));
1722 break;
1723
1724 case WebView.HitTestResult.GEO_TYPE:
1725 menu.setHeaderTitle(extra);
1726 menu.findItem(R.id.map_context_menu_id).setIntent(
1727 new Intent(Intent.ACTION_VIEW, Uri
1728 .parse(WebView.SCHEME_GEO
1729 + URLEncoder.encode(extra))));
1730 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1731 new Copy(extra));
1732 break;
1733
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001734 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1735 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001736 TextView titleView = (TextView) LayoutInflater.from(this)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001737 .inflate(android.R.layout.browser_link_context_header,
1738 null);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001739 titleView.setText(extra);
1740 menu.setHeaderView(titleView);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001741 // decide whether to show the open link in new tab option
1742 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1743 mTabControl.getTabCount() < TabControl.MAX_TABS);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001744 PackageManager pm = getPackageManager();
1745 Intent send = new Intent(Intent.ACTION_SEND);
1746 send.setType("text/plain");
1747 List<ResolveInfo> list = pm.queryIntentActivities(send,
1748 PackageManager.MATCH_DEFAULT_ONLY);
1749 menu.findItem(R.id.share_link_context_menu_id).setVisible(
1750 list.size() > 0);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001751 break;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001752
1753 case WebView.HitTestResult.IMAGE_TYPE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001754 menu.setHeaderTitle(extra);
1755 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1756 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1757 menu.findItem(R.id.download_context_menu_id).
1758 setOnMenuItemClickListener(new Download(extra));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001759 break;
1760
1761 default:
1762 Log.w(LOGTAG, "We should not get here.");
1763 break;
1764 }
1765 }
1766
1767 // Used by attachTabToContentView for the WebView's ZoomControl widget.
1768 private static final FrameLayout.LayoutParams ZOOM_PARAMS =
1769 new FrameLayout.LayoutParams(
1770 ViewGroup.LayoutParams.FILL_PARENT,
1771 ViewGroup.LayoutParams.WRAP_CONTENT,
1772 Gravity.BOTTOM);
1773
1774 // Attach the given tab to the content view.
1775 private void attachTabToContentView(TabControl.Tab t) {
1776 final WebView main = t.getWebView();
1777 // Attach the main WebView.
1778 mContentView.addView(main, COVER_SCREEN_PARAMS);
1779 // Attach the Zoom control widget and hide it.
1780 final View zoom = main.getZoomControls();
1781 mContentView.addView(zoom, ZOOM_PARAMS);
1782 zoom.setVisibility(View.GONE);
1783 // Attach the sub window if necessary
1784 attachSubWindow(t);
1785 // Request focus on the top window.
1786 t.getTopWindow().requestFocus();
1787 }
1788
1789 // Attach a sub window to the main WebView of the given tab.
1790 private void attachSubWindow(TabControl.Tab t) {
1791 // If a sub window exists, attach it to the content view.
1792 final WebView subView = t.getSubWebView();
1793 if (subView != null) {
1794 final View container = t.getSubWebViewContainer();
1795 mContentView.addView(container, COVER_SCREEN_PARAMS);
1796 subView.requestFocus();
1797 }
1798 }
1799
1800 // Remove the given tab from the content view.
1801 private void removeTabFromContentView(TabControl.Tab t) {
1802 // Remove the Zoom widget and the main WebView.
1803 mContentView.removeView(t.getWebView().getZoomControls());
1804 mContentView.removeView(t.getWebView());
1805 // Remove the sub window if it exists.
1806 if (t.getSubWebView() != null) {
1807 mContentView.removeView(t.getSubWebViewContainer());
1808 }
1809 }
1810
1811 // Remove the sub window if it exists. Also called by TabControl when the
1812 // user clicks the 'X' to dismiss a sub window.
1813 /* package */ void dismissSubWindow(TabControl.Tab t) {
1814 final WebView mainView = t.getWebView();
1815 if (t.getSubWebView() != null) {
1816 // Remove the container view and request focus on the main WebView.
1817 mContentView.removeView(t.getSubWebViewContainer());
1818 mainView.requestFocus();
1819 // Tell the TabControl to dismiss the subwindow. This will destroy
1820 // the WebView.
1821 mTabControl.dismissSubWindow(t);
1822 }
1823 }
1824
1825 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
1826 private void sendAnimateFromOverview(final TabControl.Tab tab,
1827 final boolean newTab, final String url, final int delay,
1828 final Message msg) {
1829 // Set the current tab.
1830 mTabControl.setCurrentTab(tab);
1831 // Attach the WebView so it will layout.
1832 attachTabToContentView(tab);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001833 // Set the view to invisibile for now.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001834 tab.getWebView().setVisibility(View.INVISIBLE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001835 // If there is a sub window, make it invisible too.
1836 if (tab.getSubWebView() != null) {
1837 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
1838 }
1839 // Create our fake animating view.
1840 final AnimatingView view = new AnimatingView(this, tab);
1841 // Attach it to the view system and make in invisible so it will
1842 // layout but not flash white on the screen.
1843 mContentView.addView(view, COVER_SCREEN_PARAMS);
1844 view.setVisibility(View.INVISIBLE);
1845 // Send the animate message.
1846 final HashMap map = new HashMap();
1847 map.put("view", view);
1848 map.put("url", url);
1849 map.put("msg", msg);
1850 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1851 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
1852 // Increment the count to indicate that we are in an animation.
1853 mAnimationCount++;
1854 // Remove the listener so we don't get any more tab changes.
The Android Open Source Projected217d92008-12-17 18:05:52 -08001855 mTabOverview.setListener(null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001856 mTabListener = null;
The Android Open Source Projected217d92008-12-17 18:05:52 -08001857 // Make the menu empty until the animation completes.
1858 mMenuState = EMPTY_MENU;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001859
1860 }
1861
1862 // 500ms animation with 800ms delay
1863 private static final int TAB_ANIMATION_DURATION = 500;
1864 private static final int TAB_OVERVIEW_DELAY = 800;
1865
1866 // Called by TabControl when a tab is requesting focus
1867 /* package */ void showTab(TabControl.Tab t) {
1868 // Disallow focus change during a tab animation.
1869 if (mAnimationCount > 0) {
1870 return;
1871 }
1872 int delay = 0;
1873 if (mTabOverview == null) {
1874 // Add a delay so the tab overview can be shown before the second
1875 // animation begins.
1876 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1877 tabPicker(false, mTabControl.getTabIndex(t), false);
1878 }
1879 sendAnimateFromOverview(t, false, null, delay, null);
1880 }
1881
1882 // This method does a ton of stuff. It will attempt to create a new tab
1883 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1884 // url isn't null, it will load the given url. If the tab overview is not
1885 // showing, it will animate to the tab overview, create a new tab and
1886 // animate away from it. After the animation completes, it will dispatch
1887 // the given Message. If the tab overview is already showing (i.e. this
1888 // method is called from TabListener.onClick(), the method will animate
1889 // away from the tab overview.
The Android Open Source Projected217d92008-12-17 18:05:52 -08001890 private void openTabAndShow(String url, final Message msg,
1891 boolean closeOnExit) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001892 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1893 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1894 if (newTab) {
1895 int delay = 0;
1896 // If the tab overview is up and there are animations, just load
1897 // the url.
1898 if (mTabOverview != null && mAnimationCount > 0) {
1899 if (url != null) {
1900 // We should not have a msg here since onCreateWindow
1901 // checks the animation count and every other caller passes
1902 // null.
1903 assert msg == null;
1904 // just dismiss the subwindow and load the given url.
1905 dismissSubWindow(currentTab);
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001906 currentTab.getWebView().loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001907 }
1908 } else {
1909 // show mTabOverview if it is not there.
1910 if (mTabOverview == null) {
1911 // We have to delay the animation from the tab picker by the
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001912 // length of the tab animation. Add a delay so the tab
1913 // overview can be shown before the second animation begins.
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001914 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1915 tabPicker(false, ImageGrid.NEW_TAB, false);
1916 }
1917 // Animate from the Tab overview after any animations have
1918 // finished.
The Android Open Source Projected217d92008-12-17 18:05:52 -08001919 sendAnimateFromOverview(mTabControl.createNewTab(closeOnExit),
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001920 true, url, delay, msg);
1921 }
1922 } else if (url != null) {
1923 // We should not have a msg here.
1924 assert msg == null;
1925 if (mTabOverview != null && mAnimationCount == 0) {
1926 sendAnimateFromOverview(currentTab, false, url,
1927 TAB_OVERVIEW_DELAY, null);
1928 } else {
1929 // Get rid of the subwindow if it exists
1930 dismissSubWindow(currentTab);
1931 // Load the given url.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001932 currentTab.getWebView().loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001933 }
1934 }
1935 }
1936
1937 private Animation createTabAnimation(final AnimatingView view,
1938 final View cell, boolean scaleDown) {
1939 final AnimationSet set = new AnimationSet(true);
1940 final float scaleX = (float) cell.getWidth() / view.getWidth();
1941 final float scaleY = (float) cell.getHeight() / view.getHeight();
1942 if (scaleDown) {
1943 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
1944 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
1945 cell.getTop()));
1946 } else {
1947 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
1948 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
1949 cell.getTop(), 0));
1950 }
1951 set.setDuration(TAB_ANIMATION_DURATION);
1952 set.setInterpolator(new DecelerateInterpolator());
1953 return set;
1954 }
1955
1956 // Animate to the tab overview. currentIndex tells us which position to
1957 // animate to and newIndex is the position that should be selected after
1958 // the animation completes.
1959 // If remove is true, after the animation stops, a confirmation dialog will
1960 // be displayed to the user.
1961 private void animateToTabOverview(final int newIndex, final boolean remove,
1962 final AnimatingView view) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001963 // Find the view in the ImageGrid allowing for the "New Tab" cell.
1964 int position = mTabControl.getTabIndex(view.mTab);
1965 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
1966 position++;
1967 }
1968
1969 // Offset the tab position with the first visible position to get a
1970 // number between 0 and 3.
1971 position -= mTabOverview.getFirstVisiblePosition();
1972
1973 // Grab the view that we are going to animate to.
1974 final View v = mTabOverview.getChildAt(position);
1975
1976 final Animation.AnimationListener l =
1977 new Animation.AnimationListener() {
1978 public void onAnimationStart(Animation a) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08001979 mTabOverview.requestFocus();
1980 // Clear the listener so we don't trigger a tab
1981 // selection.
1982 mTabOverview.setListener(null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001983 }
1984 public void onAnimationRepeat(Animation a) {}
1985 public void onAnimationEnd(Animation a) {
1986 // We are no longer animating so decrement the count.
1987 mAnimationCount--;
1988 // Make the view GONE so that it will not draw between
1989 // now and when the Runnable is handled.
1990 view.setVisibility(View.GONE);
1991 // Post a runnable since we can't modify the view
1992 // hierarchy during this callback.
1993 mHandler.post(new Runnable() {
1994 public void run() {
1995 // Remove the AnimatingView.
1996 mContentView.removeView(view);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001997 // Make newIndex visible.
1998 mTabOverview.setCurrentIndex(newIndex);
1999 // Restore the listener.
2000 mTabOverview.setListener(mTabListener);
2001 // Change the menu to TAB_MENU if the
2002 // ImageGrid is interactive.
2003 if (mTabOverview.isLive()) {
2004 mMenuState = R.id.TAB_MENU;
2005 mTabOverview.requestFocus();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002006 }
2007 // If a remove was requested, remove the tab.
2008 if (remove) {
2009 // During a remove, the current tab has
2010 // already changed. Remember the current one
2011 // here.
2012 final TabControl.Tab currentTab =
2013 mTabControl.getCurrentTab();
2014 // Remove the tab at newIndex from
2015 // TabControl and the tab overview.
2016 final TabControl.Tab tab =
2017 mTabControl.getTab(newIndex);
2018 mTabControl.removeTab(tab);
2019 // Restore the current tab.
2020 if (currentTab != tab) {
2021 mTabControl.setCurrentTab(currentTab);
2022 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002023 mTabOverview.remove(newIndex);
2024 // Make the current tab visible.
2025 mTabOverview.setCurrentIndex(
2026 mTabControl.getCurrentIndex());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002027 }
2028 }
2029 });
2030 }
2031 };
2032
2033 // Do an animation if there is a view to animate to.
2034 if (v != null) {
2035 // Create our animation
2036 final Animation anim = createTabAnimation(view, v, true);
2037 anim.setAnimationListener(l);
2038 // Start animating
2039 view.startAnimation(anim);
2040 } else {
2041 // If something goes wrong and we didn't find a view to animate to,
2042 // just do everything here.
2043 l.onAnimationStart(null);
2044 l.onAnimationEnd(null);
2045 }
2046 }
2047
2048 // Animate from the tab picker. The index supplied is the index to animate
2049 // from.
2050 private void animateFromTabOverview(final AnimatingView view,
2051 final boolean newTab, final String url, final Message msg) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002052 // firstVisible is the first visible tab on the screen. This helps
2053 // to know which corner of the screen the selected tab is.
2054 int firstVisible = mTabOverview.getFirstVisiblePosition();
2055 // tabPosition is the 0-based index of of the tab being opened
2056 int tabPosition = mTabControl.getTabIndex(view.mTab);
2057 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2058 // Add one to make room for the "New Tab" cell.
2059 tabPosition++;
2060 }
2061 // If this is a new tab, animate from the "New Tab" cell.
2062 if (newTab) {
2063 tabPosition = 0;
2064 }
2065 // Location corresponds to the four corners of the screen.
2066 // A new tab or 0 is upper left, 0 for an old tab is upper
2067 // right, 1 is lower left, and 2 is lower right
2068 int location = tabPosition - firstVisible;
2069
2070 // Find the view at this location.
2071 final View v = mTabOverview.getChildAt(location);
2072
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002073 // Wait until the animation completes to load the url.
2074 final Animation.AnimationListener l =
2075 new Animation.AnimationListener() {
2076 public void onAnimationStart(Animation a) {}
2077 public void onAnimationRepeat(Animation a) {}
2078 public void onAnimationEnd(Animation a) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002079 mHandler.post(new Runnable() {
2080 public void run() {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002081 mContentView.removeView(view);
2082 // Dismiss the tab overview. If the cell at the
2083 // given location is null, set the fade
2084 // parameter to true.
2085 dismissTabOverview(v == null);
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002086 TabControl.Tab t =
2087 mTabControl.getCurrentTab();
2088 WebView w = t.getWebView();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002089 if (url != null) {
2090 // Dismiss the subwindow if one exists.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002091 dismissSubWindow(t);
2092 w.loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002093 }
2094 mMenuState = R.id.MAIN_MENU;
2095 // Resume regular updates.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002096 w.resumeTimers();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002097 // Dispatch the message after the animation
2098 // completes.
2099 if (msg != null) {
2100 msg.sendToTarget();
2101 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002102 // The animation is done and the tab overview is
2103 // gone so allow key events and other animations
2104 // to begin.
2105 mAnimationCount--;
2106 // Reset all the title bar info.
2107 resetTitle();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002108 }
2109 });
2110 }
2111 };
2112
2113 if (v != null) {
2114 final Animation anim = createTabAnimation(view, v, false);
2115 // Set the listener and start animating
2116 anim.setAnimationListener(l);
2117 view.startAnimation(anim);
2118 // Make the view VISIBLE during the animation.
2119 view.setVisibility(View.VISIBLE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002120 } else {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002121 // Go ahead and load the url.
2122 l.onAnimationEnd(null);
2123 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002124 }
2125
2126 // Dismiss the tab overview applying a fade if needed.
2127 private void dismissTabOverview(final boolean fade) {
2128 if (fade) {
2129 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2130 anim.setDuration(500);
2131 anim.startNow();
2132 mTabOverview.startAnimation(anim);
2133 }
2134 // Just in case there was a problem with animating away from the tab
2135 // overview
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002136 mTabControl.getCurrentWebView().setVisibility(View.VISIBLE);
The Android Open Source Projected217d92008-12-17 18:05:52 -08002137 // Make the sub window container visible.
2138 if (mTabControl.getCurrentSubWindow() != null) {
2139 mTabControl.getCurrentTab().getSubWebViewContainer()
2140 .setVisibility(View.VISIBLE);
2141 }
2142 mContentView.removeView(mTabOverview);
2143 mTabOverview.clear();
2144 mTabOverview = null;
2145 mTabListener = null;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002146 }
2147
2148 private void openTab(String url) {
2149 if (mSettings.openInBackground()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002150 TabControl.Tab t = mTabControl.createNewTab(false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002151 if (t != null) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002152 t.getWebView().loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002153 }
2154 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002155 openTabAndShow(url, null, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002156 }
2157 }
2158
2159 private class Copy implements OnMenuItemClickListener {
2160 private CharSequence mText;
2161
2162 public boolean onMenuItemClick(MenuItem item) {
2163 copy(mText);
2164 return true;
2165 }
2166
2167 public Copy(CharSequence toCopy) {
2168 mText = toCopy;
2169 }
2170 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002171
2172 private class Download implements OnMenuItemClickListener {
2173 private String mText;
2174
2175 public boolean onMenuItemClick(MenuItem item) {
2176 onDownloadStartNoStream(mText, null, null, null, -1);
2177 return true;
2178 }
2179
2180 public Download(String toDownload) {
2181 mText = toDownload;
2182 }
2183 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002184
2185 private void copy(CharSequence text) {
2186 try {
2187 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2188 if (clip != null) {
2189 clip.setClipboardText(text);
2190 }
2191 } catch (android.os.RemoteException e) {
2192 Log.e(LOGTAG, "Copy failed", e);
2193 }
2194 }
2195
2196 /**
2197 * Resets the browser title-view to whatever it must be (for example, if we
2198 * load a page from history).
2199 */
2200 private void resetTitle() {
2201 resetLockIcon();
2202 resetTitleIconAndProgress();
2203 }
2204
2205 /**
2206 * Resets the browser title-view to whatever it must be
2207 * (for example, if we had a loading error)
2208 * When we have a new page, we call resetTitle, when we
2209 * have to reset the titlebar to whatever it used to be
2210 * (for example, if the user chose to stop loading), we
2211 * call resetTitleAndRevertLockIcon.
2212 */
2213 /* package */ void resetTitleAndRevertLockIcon() {
2214 revertLockIcon();
2215 resetTitleIconAndProgress();
2216 }
2217
2218 /**
2219 * Reset the title, favicon, and progress.
2220 */
2221 private void resetTitleIconAndProgress() {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002222 WebView current = mTabControl.getCurrentWebView();
2223 if (current == null) {
2224 return;
2225 }
2226 resetTitleAndIcon(current);
2227 int progress = current.getProgress();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002228 mInLoad = (progress != 100);
2229 updateInLoadMenuItems();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002230 mWebChromeClient.onProgressChanged(current, progress);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002231 }
2232
2233 // Reset the title and the icon based on the given item.
2234 private void resetTitleAndIcon(WebView view) {
2235 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2236 if (item != null) {
2237 setUrlTitle(item.getUrl(), item.getTitle());
2238 setFavicon(item.getFavicon());
2239 } else {
2240 setUrlTitle(null, null);
2241 setFavicon(null);
2242 }
2243 }
2244
2245 /**
2246 * Sets a title composed of the URL and the title string.
2247 * @param url The URL of the site being loaded.
2248 * @param title The title of the site being loaded.
2249 */
2250 private void setUrlTitle(String url, String title) {
2251 mUrl = url;
2252 mTitle = title;
2253
The Android Open Source Projected217d92008-12-17 18:05:52 -08002254 // While the tab overview is animating or being shown, block changes
2255 // to the title.
2256 if (mAnimationCount == 0 && mTabOverview == null) {
2257 setTitle(buildUrlTitle(url, title));
2258 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002259 }
2260
2261 /**
2262 * Builds and returns the page title, which is some
2263 * combination of the page URL and title.
2264 * @param url The URL of the site being loaded.
2265 * @param title The title of the site being loaded.
2266 * @return The page title.
2267 */
2268 private String buildUrlTitle(String url, String title) {
2269 String urlTitle = "";
2270
2271 if (url != null) {
2272 String titleUrl = buildTitleUrl(url);
2273
2274 if (title != null && 0 < title.length()) {
2275 if (titleUrl != null && 0 < titleUrl.length()) {
2276 urlTitle = titleUrl + ": " + title;
2277 } else {
2278 urlTitle = title;
2279 }
2280 } else {
2281 if (titleUrl != null) {
2282 urlTitle = titleUrl;
2283 }
2284 }
2285 }
2286
2287 return urlTitle;
2288 }
2289
2290 /**
2291 * @param url The URL to build a title version of the URL from.
2292 * @return The title version of the URL or null if fails.
2293 * The title version of the URL can be either the URL hostname,
2294 * or the hostname with an "https://" prefix (for secure URLs),
2295 * or an empty string if, for example, the URL in question is a
2296 * file:// URL with no hostname.
2297 */
2298 private static String buildTitleUrl(String url) {
2299 String titleUrl = null;
2300
2301 if (url != null) {
2302 try {
2303 // parse the url string
2304 URL urlObj = new URL(url);
2305 if (urlObj != null) {
2306 titleUrl = "";
2307
2308 String protocol = urlObj.getProtocol();
2309 String host = urlObj.getHost();
2310
2311 if (host != null && 0 < host.length()) {
2312 titleUrl = host;
2313 if (protocol != null) {
2314 // if a secure site, add an "https://" prefix!
2315 if (protocol.equalsIgnoreCase("https")) {
2316 titleUrl = protocol + "://" + host;
2317 }
2318 }
2319 }
2320 }
2321 } catch (MalformedURLException e) {}
2322 }
2323
2324 return titleUrl;
2325 }
2326
2327 // Set the favicon in the title bar.
2328 private void setFavicon(Bitmap icon) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002329 // While the tab overview is animating or being shown, block changes to
2330 // the favicon.
2331 if (mAnimationCount > 0 || mTabOverview != null) {
2332 return;
2333 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002334 Drawable[] array = new Drawable[2];
2335 PaintDrawable p = new PaintDrawable(Color.WHITE);
2336 p.setCornerRadius(3f);
2337 array[0] = p;
2338 if (icon == null) {
2339 array[1] = mGenericFavicon;
2340 } else {
2341 array[1] = new BitmapDrawable(icon);
2342 }
2343 LayerDrawable d = new LayerDrawable(array);
2344 d.setLayerInset(1, 2, 2, 2, 2);
2345 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
2346 }
2347
2348 /**
2349 * Saves the current lock-icon state before resetting
2350 * the lock icon. If we have an error, we may need to
2351 * roll back to the previous state.
2352 */
2353 private void saveLockIcon() {
2354 mPrevLockType = mLockIconType;
2355 }
2356
2357 /**
2358 * Reverts the lock-icon state to the last saved state,
2359 * for example, if we had an error, and need to cancel
2360 * the load.
2361 */
2362 private void revertLockIcon() {
2363 mLockIconType = mPrevLockType;
2364
2365 if (Config.LOGV) {
2366 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2367 " revert lock icon to " + mLockIconType);
2368 }
2369
2370 updateLockIconImage(mLockIconType);
2371 }
2372
The Android Open Source Projected217d92008-12-17 18:05:52 -08002373 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002374 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2375 // Animate to the tab picker, remove the current tab, then
2376 // animate away from the tab picker to the parent WebView.
The Android Open Source Projected217d92008-12-17 18:05:52 -08002377 tabPicker(false, indexFrom, remove);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002378 // Change to the parent tab
2379 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2380 if (tab != null) {
2381 sendAnimateFromOverview(tab, false, null, delay, null);
2382 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002383 // Increment this here so that no other animations can happen in
2384 // between the end of the tab picker transition and the beginning
2385 // of openTabAndShow. This has a matching decrement in the handler
2386 // of OPEN_TAB_AND_SHOW.
2387 mAnimationCount++;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002388 // Send a message to open a new tab.
2389 mHandler.sendMessageDelayed(
2390 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2391 mSettings.getHomePage()), delay);
2392 }
2393 }
2394
2395 private void goBackOnePageOrQuit() {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002396 TabControl.Tab current = mTabControl.getCurrentTab();
2397 if (current == null) {
2398 /*
2399 * Instead of finishing the activity, simply push this to the back
2400 * of the stack and let ActivityManager to choose the foreground
2401 * activity. As BrowserActivity is singleTask, it will be always the
2402 * root of the task. So we can use either true or false for
2403 * moveTaskToBack().
2404 */
2405 moveTaskToBack(true);
2406 }
2407 WebView w = current.getWebView();
2408 if (w.canGoBack()) {
2409 w.goBack();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002410 } else {
2411 // Check to see if we are closing a window that was created by
2412 // another window. If so, we switch back to that window.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002413 TabControl.Tab parent = current.getParentTab();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002414 if (parent != null) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002415 switchTabs(mTabControl.getCurrentIndex(),
2416 mTabControl.getTabIndex(parent), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002417 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002418 if (current.closeOnExit()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002419 if (mTabControl.getTabCount() == 1) {
2420 finish();
2421 return;
2422 }
2423 // call pauseWebView() now, we won't be able to call it in
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002424 // onPause() as the WebView won't be valid.
The Android Open Source Projected217d92008-12-17 18:05:52 -08002425 pauseWebView();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002426 removeTabFromContentView(current);
2427 mTabControl.removeTab(current);
The Android Open Source Projected217d92008-12-17 18:05:52 -08002428 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002429 /*
2430 * Instead of finishing the activity, simply push this to the back
2431 * of the stack and let ActivityManager to choose the foreground
2432 * activity. As BrowserActivity is singleTask, it will be always the
2433 * root of the task. So we can use either true or false for
2434 * moveTaskToBack().
2435 */
2436 moveTaskToBack(true);
2437 }
2438 }
2439 }
2440
2441 public KeyTracker.State onKeyTracker(int keyCode,
2442 KeyEvent event,
2443 KeyTracker.Stage stage,
2444 int duration) {
2445 // if onKeyTracker() is called after activity onStop()
2446 // because of accumulated key events,
2447 // we should ignore it as browser is not active any more.
2448 WebView topWindow = getTopWindow();
2449 if (topWindow == null)
2450 return KeyTracker.State.NOT_TRACKING;
2451
2452 if (keyCode == KeyEvent.KEYCODE_BACK) {
2453 // During animations, block the back key so that other animations
2454 // are not triggered and so that we don't end up destroying all the
2455 // WebViews before finishing the animation.
2456 if (mAnimationCount > 0) {
2457 return KeyTracker.State.DONE_TRACKING;
2458 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002459 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2460 loadHistory();
2461 return KeyTracker.State.DONE_TRACKING;
2462 } else if (stage == KeyTracker.Stage.UP) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002463 // FIXME: Currently, we do not have a notion of the
2464 // history picker for the subwindow, but maybe we
2465 // should?
2466 WebView subwindow = mTabControl.getCurrentSubWindow();
2467 if (subwindow != null) {
2468 if (subwindow.canGoBack()) {
2469 subwindow.goBack();
2470 } else {
2471 dismissSubWindow(mTabControl.getCurrentTab());
2472 }
2473 } else {
2474 goBackOnePageOrQuit();
2475 }
2476 return KeyTracker.State.DONE_TRACKING;
2477 }
2478 return KeyTracker.State.KEEP_TRACKING;
2479 }
2480 return KeyTracker.State.NOT_TRACKING;
2481 }
2482
2483 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2484 if (keyCode == KeyEvent.KEYCODE_MENU) {
2485 mMenuIsDown = true;
2486 }
2487 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2488 if (!handled) {
2489 switch (keyCode) {
2490 case KeyEvent.KEYCODE_SPACE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002491 if (event.isShiftPressed()) {
2492 getTopWindow().pageUp(false);
2493 } else {
2494 getTopWindow().pageDown(false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002495 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002496 handled = true;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002497 break;
2498
2499 default:
2500 break;
2501 }
2502 }
2503 return handled || super.onKeyDown(keyCode, event);
2504 }
2505
2506 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2507 if (keyCode == KeyEvent.KEYCODE_MENU) {
2508 mMenuIsDown = false;
2509 }
2510 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2511 }
2512
2513 private void stopLoading() {
2514 resetTitleAndRevertLockIcon();
2515 WebView w = getTopWindow();
2516 w.stopLoading();
2517 mWebViewClient.onPageFinished(w, w.getUrl());
2518
2519 cancelStopToast();
2520 mStopToast = Toast
2521 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2522 mStopToast.show();
2523 }
2524
2525 private void cancelStopToast() {
2526 if (mStopToast != null) {
2527 mStopToast.cancel();
2528 mStopToast = null;
2529 }
2530 }
2531
The Android Open Source Projected217d92008-12-17 18:05:52 -08002532 private void loadHistory() {
2533 Intent intent = new Intent(this, BrowserHistoryPage.class);
2534 intent.putExtra("maxTabsOpen",
2535 mTabControl.getTabCount() >= TabControl.MAX_TABS);
2536 startActivityForResult(intent, CLASSIC_HISTORY_PAGE);
2537 }
2538
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002539 // called by a non-UI thread to post the message
2540 public void postMessage(int what, int arg1, int arg2, Object obj) {
2541 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2542 }
2543
2544 // public message ids
2545 public final static int LOAD_URL = 1001;
2546 public final static int STOP_LOAD = 1002;
2547
2548 // Message Ids
2549 private static final int JS_CONFIRM = 101;
2550 private static final int FOCUS_NODE_HREF = 102;
The Android Open Source Projected217d92008-12-17 18:05:52 -08002551 private static final int CANCEL_CREDS_REQUEST = 103;
2552 private static final int ANIMATE_FROM_OVERVIEW = 104;
2553 private static final int ANIMATE_TO_OVERVIEW = 105;
2554 private static final int OPEN_TAB_AND_SHOW = 106;
2555 private static final int CHECK_MEMORY = 107;
2556 private static final int RELEASE_WAKELOCK = 108;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002557
2558 // Private handler for handling javascript and saving passwords
2559 private Handler mHandler = new Handler() {
2560
2561 public void handleMessage(Message msg) {
2562 switch (msg.what) {
2563 case JS_CONFIRM:
2564 JsResult res = (JsResult) msg.obj;
2565 if (msg.arg1 == 0) {
2566 res.cancel();
2567 } else {
2568 res.confirm();
2569 }
2570 break;
2571
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002572 case ANIMATE_FROM_OVERVIEW:
2573 final HashMap map = (HashMap) msg.obj;
2574 animateFromTabOverview((AnimatingView) map.get("view"),
2575 msg.arg1 == 1, (String) map.get("url"),
2576 (Message) map.get("msg"));
2577 break;
2578
2579 case ANIMATE_TO_OVERVIEW:
2580 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2581 (AnimatingView) msg.obj);
2582 break;
2583
2584 case OPEN_TAB_AND_SHOW:
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002585 // Decrement mAnimationCount before openTabAndShow because
2586 // the method relies on the value being 0 to start the next
2587 // animation.
2588 mAnimationCount--;
The Android Open Source Projected217d92008-12-17 18:05:52 -08002589 openTabAndShow((String) msg.obj, null, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002590 break;
2591
2592 case FOCUS_NODE_HREF:
2593 String url = (String) msg.getData().get("url");
2594 if (url == null || url.length() == 0) {
2595 break;
2596 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002597 HashMap focusNodeMap = (HashMap) msg.obj;
2598 WebView view = (WebView) focusNodeMap.get("webview");
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002599 // Only apply the action if the top window did not change.
2600 if (getTopWindow() != view) {
2601 break;
2602 }
2603 switch (msg.arg1) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002604 case R.id.open_context_menu_id:
2605 case R.id.view_image_context_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002606 loadURL(getTopWindow(), url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002607 break;
2608 case R.id.open_newtab_context_menu_id:
2609 openTab(url);
2610 break;
2611 case R.id.bookmark_context_menu_id:
2612 Intent intent = new Intent(BrowserActivity.this,
2613 AddBookmarkPage.class);
2614 intent.putExtra("url", url);
2615 startActivity(intent);
2616 break;
2617 case R.id.share_link_context_menu_id:
2618 Browser.sendString(BrowserActivity.this, url);
2619 break;
2620 case R.id.copy_link_context_menu_id:
2621 copy(url);
2622 break;
2623 case R.id.save_link_context_menu_id:
2624 case R.id.download_context_menu_id:
2625 onDownloadStartNoStream(url, null, null, null, -1);
2626 break;
2627 }
2628 break;
2629
2630 case LOAD_URL:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002631 loadURL(getTopWindow(), (String) msg.obj);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002632 break;
2633
2634 case STOP_LOAD:
2635 stopLoading();
2636 break;
2637
2638 case CANCEL_CREDS_REQUEST:
2639 resumeAfterCredentials();
2640 break;
2641
2642 case CHECK_MEMORY:
2643 // reschedule to check memory condition
2644 mHandler.removeMessages(CHECK_MEMORY);
2645 mHandler.sendMessageDelayed(mHandler.obtainMessage
2646 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2647 checkMemory();
2648 break;
2649
2650 case RELEASE_WAKELOCK:
2651 if (mWakeLock.isHeld()) {
2652 mWakeLock.release();
2653 }
2654 break;
2655 }
2656 }
2657 };
2658
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002659 // -------------------------------------------------------------------------
2660 // WebViewClient implementation.
2661 //-------------------------------------------------------------------------
2662
2663 // Use in overrideUrlLoading
2664 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2665 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2666 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2667 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2668
2669 /* package */ WebViewClient getWebViewClient() {
2670 return mWebViewClient;
2671 }
2672
The Android Open Source Projected217d92008-12-17 18:05:52 -08002673 private void updateIcon(String url, Bitmap icon) {
2674 if (icon != null) {
2675 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2676 url, icon);
2677 }
2678 setFavicon(icon);
2679 }
2680
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002681 private final WebViewClient mWebViewClient = new WebViewClient() {
2682 @Override
2683 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2684 resetLockIcon(url);
2685 setUrlTitle(url, null);
The Android Open Source Projected217d92008-12-17 18:05:52 -08002686 // Call updateIcon instead of setFavicon so the bookmark
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002687 // database can be updated.
The Android Open Source Projected217d92008-12-17 18:05:52 -08002688 updateIcon(url, favicon);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002689
2690 if (mSettings.isTracing() == true) {
2691 // FIXME: we should save the trace file somewhere other than data.
2692 // I can't use "/tmp" as it competes for system memory.
2693 File file = getDir("browserTrace", 0);
2694 String baseDir = file.getPath();
2695 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2696 String host;
2697 try {
2698 WebAddress uri = new WebAddress(url);
2699 host = uri.mHost;
2700 } catch (android.net.ParseException ex) {
2701 host = "unknown_host";
2702 }
2703 host = host.replace('.', '_');
2704 baseDir = baseDir + host;
2705 file = new File(baseDir+".data");
2706 if (file.exists() == true) {
2707 file.delete();
2708 }
2709 file = new File(baseDir+".key");
2710 if (file.exists() == true) {
2711 file.delete();
2712 }
2713 mInTrace = true;
2714 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2715 }
2716
2717 // Performance probe
2718 if (false) {
2719 mStart = SystemClock.uptimeMillis();
2720 mProcessStart = Process.getElapsedCpuTime();
2721 long[] sysCpu = new long[7];
2722 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2723 sysCpu, null)) {
2724 mUserStart = sysCpu[0] + sysCpu[1];
2725 mSystemStart = sysCpu[2];
2726 mIdleStart = sysCpu[3];
2727 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2728 }
2729 mUiStart = SystemClock.currentThreadTimeMillis();
2730 }
2731
2732 if (!mPageStarted) {
2733 mPageStarted = true;
2734 // if onResume() has been called, resumeWebView() does nothing.
2735 resumeWebView();
2736 }
2737
2738 // reset sync timer to avoid sync starts during loading a page
2739 CookieSyncManager.getInstance().resetSync();
2740
2741 mInLoad = true;
2742 updateInLoadMenuItems();
2743
2744 // schedule to check memory condition
2745 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
2746 CHECK_MEMORY_INTERVAL);
2747 }
2748
2749 @Override
2750 public void onPageFinished(WebView view, String url) {
2751 // Reset the title and icon in case we stopped a provisional
2752 // load.
2753 resetTitleAndIcon(view);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002754
2755 // Update the lock icon image only once we are done loading
2756 updateLockIconImage(mLockIconType);
2757
2758 // Performance probe
2759 if (false) {
2760 long[] sysCpu = new long[7];
2761 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2762 sysCpu, null)) {
2763 String uiInfo = "UI thread used "
2764 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2765 + " ms";
2766 if (Config.LOGD) {
2767 Log.d(LOGTAG, uiInfo);
2768 }
2769 //The string that gets written to the log
2770 String performanceString = "It took total "
2771 + (SystemClock.uptimeMillis() - mStart)
2772 + " ms clock time to load the page."
2773 + "\nbrowser process used "
2774 + (Process.getElapsedCpuTime() - mProcessStart)
2775 + " ms, user processes used "
2776 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2777 + " ms, kernel used "
2778 + (sysCpu[2] - mSystemStart) * 10
2779 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2780 + " ms and irq took "
2781 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2782 * 10 + " ms, " + uiInfo;
2783 if (Config.LOGD) {
2784 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2785 }
2786 if (url != null) {
2787 // strip the url to maintain consistency
2788 String newUrl = new String(url);
2789 if (newUrl.startsWith("http://www.")) {
2790 newUrl = newUrl.substring(11);
2791 } else if (newUrl.startsWith("http://")) {
2792 newUrl = newUrl.substring(7);
2793 } else if (newUrl.startsWith("https://www.")) {
2794 newUrl = newUrl.substring(12);
2795 } else if (newUrl.startsWith("https://")) {
2796 newUrl = newUrl.substring(8);
2797 }
2798 if (Config.LOGD) {
2799 Log.d(LOGTAG, newUrl + " loaded");
2800 }
2801 /*
2802 if (sWhiteList.contains(newUrl)) {
2803 // The string that gets pushed to the statistcs
2804 // service
2805 performanceString = performanceString
2806 + "\nWebpage: "
2807 + newUrl
2808 + "\nCarrier: "
2809 + android.os.SystemProperties
2810 .get("gsm.sim.operator.alpha");
2811 if (mWebView != null
2812 && mWebView.getContext() != null
2813 && mWebView.getContext().getSystemService(
2814 Context.CONNECTIVITY_SERVICE) != null) {
2815 ConnectivityManager cManager =
2816 (ConnectivityManager) mWebView
2817 .getContext().getSystemService(
2818 Context.CONNECTIVITY_SERVICE);
2819 NetworkInfo nInfo = cManager
2820 .getActiveNetworkInfo();
2821 if (nInfo != null) {
2822 performanceString = performanceString
2823 + "\nNetwork Type: "
2824 + nInfo.getType().toString();
2825 }
2826 }
2827 Checkin.logEvent(mResolver,
2828 Checkin.Events.Tag.WEBPAGE_LOAD,
2829 performanceString);
2830 Log.w(LOGTAG, "pushed to the statistics service");
2831 }
2832 */
2833 }
2834 }
2835 }
2836
2837 if (mInTrace) {
2838 mInTrace = false;
2839 Debug.stopMethodTracing();
2840 }
2841
2842 if (mPageStarted) {
2843 mPageStarted = false;
2844 // pauseWebView() will do nothing and return false if onPause()
2845 // is not called yet.
2846 if (pauseWebView()) {
2847 if (mWakeLock.isHeld()) {
2848 mHandler.removeMessages(RELEASE_WAKELOCK);
2849 mWakeLock.release();
2850 }
2851 }
2852 }
2853
2854 if (mInLoad) {
2855 mInLoad = false;
2856 updateInLoadMenuItems();
2857 }
2858
2859 mHandler.removeMessages(CHECK_MEMORY);
2860 checkMemory();
2861 }
2862
2863 // return true if want to hijack the url to let another app to handle it
2864 @Override
2865 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2866 if (url.startsWith(SCHEME_WTAI)) {
2867 // wtai://wp/mc;number
2868 // number=string(phone-number)
2869 if (url.startsWith(SCHEME_WTAI_MC)) {
2870 Intent intent = new Intent(Intent.ACTION_VIEW,
2871 Uri.parse(WebView.SCHEME_TEL +
2872 url.substring(SCHEME_WTAI_MC.length())));
2873 startActivity(intent);
2874 return true;
2875 }
2876 // wtai://wp/sd;dtmf
2877 // dtmf=string(dialstring)
2878 if (url.startsWith(SCHEME_WTAI_SD)) {
2879 // TODO
2880 // only send when there is active voice connection
2881 return false;
2882 }
2883 // wtai://wp/ap;number;name
2884 // number=string(phone-number)
2885 // name=string
2886 if (url.startsWith(SCHEME_WTAI_AP)) {
2887 // TODO
2888 return false;
2889 }
2890 }
2891
2892 Uri uri;
2893 try {
2894 uri = Uri.parse(url);
2895 } catch (IllegalArgumentException ex) {
2896 return false;
2897 }
2898
2899 // check whether other activities want to handle this url
2900 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
2901 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2902 try {
2903 if (startActivityIfNeeded(intent, -1)) {
2904 return true;
2905 }
2906 } catch (ActivityNotFoundException ex) {
2907 // ignore the error. If no application can handle the URL,
2908 // eg about:blank, assume the browser can handle it.
2909 }
2910
2911 if (mMenuIsDown) {
2912 openTab(url);
2913 closeOptionsMenu();
2914 return true;
2915 }
2916
2917 return false;
2918 }
2919
2920 /**
2921 * Updates the lock icon. This method is called when we discover another
2922 * resource to be loaded for this page (for example, javascript). While
2923 * we update the icon type, we do not update the lock icon itself until
2924 * we are done loading, it is slightly more secure this way.
2925 */
2926 @Override
2927 public void onLoadResource(WebView view, String url) {
2928 if (url != null && url.length() > 0) {
2929 // It is only if the page claims to be secure
2930 // that we may have to update the lock:
2931 if (mLockIconType == LOCK_ICON_SECURE) {
2932 // If NOT a 'safe' url, change the lock to mixed content!
2933 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2934 mLockIconType = LOCK_ICON_MIXED;
2935 if (Config.LOGV) {
2936 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2937 " updated lock icon to " + mLockIconType + " due to " + url);
2938 }
2939 }
2940 }
2941 }
2942 }
2943
2944 /**
2945 * Show the dialog, asking the user if they would like to continue after
2946 * an excessive number of HTTP redirects.
2947 */
2948 @Override
2949 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2950 final Message continueMsg) {
2951 new AlertDialog.Builder(BrowserActivity.this)
2952 .setTitle(R.string.browserFrameRedirect)
2953 .setMessage(R.string.browserFrame307Post)
2954 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2955 public void onClick(DialogInterface dialog, int which) {
2956 continueMsg.sendToTarget();
2957 }})
2958 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2959 public void onClick(DialogInterface dialog, int which) {
2960 cancelMsg.sendToTarget();
2961 }})
2962 .setOnCancelListener(new OnCancelListener() {
2963 public void onCancel(DialogInterface dialog) {
2964 cancelMsg.sendToTarget();
2965 }})
2966 .show();
2967 }
2968
2969 /**
2970 * Show a dialog informing the user of the network error reported by
2971 * WebCore.
2972 */
2973 @Override
2974 public void onReceivedError(WebView view, int errorCode,
2975 String description, String failingUrl) {
2976 if (errorCode != EventHandler.ERROR_LOOKUP &&
2977 errorCode != EventHandler.ERROR_CONNECT &&
2978 errorCode != EventHandler.ERROR_BAD_URL &&
The Android Open Source Projected217d92008-12-17 18:05:52 -08002979 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002980 errorCode != EventHandler.FILE_ERROR) {
2981 new AlertDialog.Builder(BrowserActivity.this)
2982 .setTitle((errorCode == EventHandler.FILE_NOT_FOUND_ERROR) ?
2983 R.string.browserFrameFileErrorLabel :
2984 R.string.browserFrameNetworkErrorLabel)
2985 .setMessage(description)
2986 .setPositiveButton(R.string.ok, null)
2987 .show();
2988 }
2989 Log.e(LOGTAG, "onReceivedError code:"+errorCode+" "+description);
2990
2991 // We need to reset the title after an error.
2992 resetTitleAndRevertLockIcon();
2993 }
2994
2995 /**
2996 * Check with the user if it is ok to resend POST data as the page they
2997 * are trying to navigate to is the result of a POST.
2998 */
2999 @Override
3000 public void onFormResubmission(WebView view, final Message dontResend,
3001 final Message resend) {
3002 new AlertDialog.Builder(BrowserActivity.this)
3003 .setTitle(R.string.browserFrameFormResubmitLabel)
3004 .setMessage(R.string.browserFrameFormResubmitMessage)
3005 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3006 public void onClick(DialogInterface dialog, int which) {
3007 resend.sendToTarget();
3008 }})
3009 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3010 public void onClick(DialogInterface dialog, int which) {
3011 dontResend.sendToTarget();
3012 }})
3013 .setOnCancelListener(new OnCancelListener() {
3014 public void onCancel(DialogInterface dialog) {
3015 dontResend.sendToTarget();
3016 }})
3017 .show();
3018 }
3019
3020 /**
3021 * Insert the url into the visited history database.
3022 * @param url The url to be inserted.
3023 * @param isReload True if this url is being reloaded.
3024 * FIXME: Not sure what to do when reloading the page.
3025 */
3026 @Override
3027 public void doUpdateVisitedHistory(WebView view, String url,
3028 boolean isReload) {
3029 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3030 return;
3031 }
3032 Browser.updateVisitedHistory(mResolver, url, true);
3033 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3034 }
3035
3036 /**
3037 * Displays SSL error(s) dialog to the user.
3038 */
3039 @Override
3040 public void onReceivedSslError(
3041 final WebView view, final SslErrorHandler handler, final SslError error) {
3042
3043 if (mSettings.showSecurityWarnings()) {
3044 final LayoutInflater factory =
3045 LayoutInflater.from(BrowserActivity.this);
3046 final View warningsView =
3047 factory.inflate(R.layout.ssl_warnings, null);
3048 final LinearLayout placeholder =
3049 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3050
3051 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3052 LinearLayout ll = (LinearLayout)factory
3053 .inflate(R.layout.ssl_warning, null);
3054 ((TextView)ll.findViewById(R.id.warning))
3055 .setText(R.string.ssl_untrusted);
3056 placeholder.addView(ll);
3057 }
3058
3059 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3060 LinearLayout ll = (LinearLayout)factory
3061 .inflate(R.layout.ssl_warning, null);
3062 ((TextView)ll.findViewById(R.id.warning))
3063 .setText(R.string.ssl_mismatch);
3064 placeholder.addView(ll);
3065 }
3066
3067 if (error.hasError(SslError.SSL_EXPIRED)) {
3068 LinearLayout ll = (LinearLayout)factory
3069 .inflate(R.layout.ssl_warning, null);
3070 ((TextView)ll.findViewById(R.id.warning))
3071 .setText(R.string.ssl_expired);
3072 placeholder.addView(ll);
3073 }
3074
3075 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3076 LinearLayout ll = (LinearLayout)factory
3077 .inflate(R.layout.ssl_warning, null);
3078 ((TextView)ll.findViewById(R.id.warning))
3079 .setText(R.string.ssl_not_yet_valid);
3080 placeholder.addView(ll);
3081 }
3082
3083 new AlertDialog.Builder(BrowserActivity.this)
3084 .setTitle(R.string.security_warning)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003085 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003086 .setView(warningsView)
3087 .setPositiveButton(R.string.ssl_continue,
3088 new DialogInterface.OnClickListener() {
3089 public void onClick(DialogInterface dialog, int whichButton) {
3090 handler.proceed();
3091 }
3092 })
3093 .setNeutralButton(R.string.view_certificate,
3094 new DialogInterface.OnClickListener() {
3095 public void onClick(DialogInterface dialog, int whichButton) {
3096 showSSLCertificateOnError(view, handler, error);
3097 }
3098 })
3099 .setNegativeButton(R.string.cancel,
3100 new DialogInterface.OnClickListener() {
3101 public void onClick(DialogInterface dialog, int whichButton) {
3102 handler.cancel();
3103 BrowserActivity.this.resetTitleAndRevertLockIcon();
3104 }
3105 })
3106 .setOnCancelListener(
3107 new DialogInterface.OnCancelListener() {
3108 public void onCancel(DialogInterface dialog) {
3109 handler.cancel();
3110 BrowserActivity.this.resetTitleAndRevertLockIcon();
3111 }
3112 })
3113 .show();
3114 } else {
3115 handler.proceed();
3116 }
3117 }
3118
3119 /**
3120 * Handles an HTTP authentication request.
3121 *
3122 * @param handler The authentication handler
3123 * @param host The host
3124 * @param realm The realm
3125 */
3126 @Override
3127 public void onReceivedHttpAuthRequest(WebView view,
3128 final HttpAuthHandler handler, final String host, final String realm) {
3129 String username = null;
3130 String password = null;
3131
3132 boolean reuseHttpAuthUsernamePassword =
3133 handler.useHttpAuthUsernamePassword();
3134
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003135 if (reuseHttpAuthUsernamePassword &&
3136 (mTabControl.getCurrentWebView() != null)) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003137 String[] credentials =
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003138 mTabControl.getCurrentWebView()
3139 .getHttpAuthUsernamePassword(host, realm);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003140 if (credentials != null && credentials.length == 2) {
3141 username = credentials[0];
3142 password = credentials[1];
3143 }
3144 }
3145
3146 if (username != null && password != null) {
3147 handler.proceed(username, password);
3148 } else {
3149 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3150 }
3151 }
3152
3153 @Override
3154 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3155 if (mMenuIsDown) {
3156 // only check shortcut key when MENU is held
3157 return getWindow().isShortcutKey(event.getKeyCode(), event);
3158 } else {
3159 return false;
3160 }
3161 }
3162
3163 @Override
3164 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003165 if (view != mTabControl.getCurrentTopWebView()) {
3166 return;
3167 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003168 if (event.isDown()) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003169 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003170 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003171 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003172 }
3173 }
3174 };
3175
3176 //--------------------------------------------------------------------------
3177 // WebChromeClient implementation
3178 //--------------------------------------------------------------------------
3179
3180 /* package */ WebChromeClient getWebChromeClient() {
3181 return mWebChromeClient;
3182 }
3183
3184 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3185 // Helper method to create a new tab or sub window.
3186 private void createWindow(final boolean dialog, final Message msg) {
3187 if (dialog) {
3188 mTabControl.createSubWindow();
3189 final TabControl.Tab t = mTabControl.getCurrentTab();
3190 attachSubWindow(t);
3191 WebView.WebViewTransport transport =
3192 (WebView.WebViewTransport) msg.obj;
3193 transport.setWebView(t.getSubWebView());
3194 msg.sendToTarget();
3195 } else {
3196 final TabControl.Tab parent = mTabControl.getCurrentTab();
3197 // openTabAndShow will dispatch the message after creating the
3198 // new WebView. This will prevent another request from coming
3199 // in during the animation.
The Android Open Source Projected217d92008-12-17 18:05:52 -08003200 openTabAndShow(null, msg, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003201 parent.addChildTab(mTabControl.getCurrentTab());
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003202 WebView.WebViewTransport transport =
3203 (WebView.WebViewTransport) msg.obj;
3204 transport.setWebView(mTabControl.getCurrentWebView());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003205 }
3206 }
3207
3208 @Override
3209 public boolean onCreateWindow(WebView view, final boolean dialog,
3210 final boolean userGesture, final Message resultMsg) {
3211 // Ignore these requests during tab animations or if the tab
3212 // overview is showing.
3213 if (mAnimationCount > 0 || mTabOverview != null) {
3214 return false;
3215 }
3216 // Short-circuit if we can't create any more tabs or sub windows.
3217 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3218 new AlertDialog.Builder(BrowserActivity.this)
3219 .setTitle(R.string.too_many_subwindows_dialog_title)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003220 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003221 .setMessage(R.string.too_many_subwindows_dialog_message)
3222 .setPositiveButton(R.string.ok, null)
3223 .show();
3224 return false;
3225 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3226 new AlertDialog.Builder(BrowserActivity.this)
3227 .setTitle(R.string.too_many_windows_dialog_title)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003228 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003229 .setMessage(R.string.too_many_windows_dialog_message)
3230 .setPositiveButton(R.string.ok, null)
3231 .show();
3232 return false;
3233 }
3234
3235 // Short-circuit if this was a user gesture.
3236 if (userGesture) {
3237 // createWindow will call openTabAndShow for new Windows and
3238 // that will call tabPicker which will increment
3239 // mAnimationCount.
3240 createWindow(dialog, resultMsg);
3241 return true;
3242 }
3243
3244 // Allow the popup and create the appropriate window.
3245 final AlertDialog.OnClickListener allowListener =
3246 new AlertDialog.OnClickListener() {
3247 public void onClick(DialogInterface d,
3248 int which) {
3249 // Same comment as above for setting
3250 // mAnimationCount.
3251 createWindow(dialog, resultMsg);
3252 // Since we incremented mAnimationCount while the
3253 // dialog was up, we have to decrement it here.
3254 mAnimationCount--;
3255 }
3256 };
3257
3258 // Block the popup by returning a null WebView.
3259 final AlertDialog.OnClickListener blockListener =
3260 new AlertDialog.OnClickListener() {
3261 public void onClick(DialogInterface d, int which) {
3262 resultMsg.sendToTarget();
3263 // We are not going to trigger an animation so
3264 // unblock keys and animation requests.
3265 mAnimationCount--;
3266 }
3267 };
3268
3269 // Build a confirmation dialog to display to the user.
3270 final AlertDialog d =
3271 new AlertDialog.Builder(BrowserActivity.this)
3272 .setTitle(R.string.attention)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003273 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003274 .setMessage(R.string.popup_window_attempt)
3275 .setPositiveButton(R.string.allow, allowListener)
3276 .setNegativeButton(R.string.block, blockListener)
3277 .setCancelable(false)
3278 .create();
3279
3280 // Show the confirmation dialog.
3281 d.show();
3282 // We want to increment mAnimationCount here to prevent a
3283 // potential race condition. If the user allows a pop-up from a
3284 // site and that pop-up then triggers another pop-up, it is
3285 // possible to get the BACK key between here and when the dialog
3286 // appears.
3287 mAnimationCount++;
3288 return true;
3289 }
3290
3291 @Override
3292 public void onCloseWindow(WebView window) {
3293 final int currentIndex = mTabControl.getCurrentIndex();
3294 final TabControl.Tab parent =
3295 mTabControl.getCurrentTab().getParentTab();
3296 if (parent != null) {
3297 // JavaScript can only close popup window.
The Android Open Source Projected217d92008-12-17 18:05:52 -08003298 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003299 }
3300 }
3301
3302 @Override
3303 public void onProgressChanged(WebView view, int newProgress) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003304 // Block progress updates to the title bar while the tab overview
3305 // is animating or being displayed.
3306 if (mAnimationCount == 0 && mTabOverview == null) {
3307 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3308 newProgress * 100);
3309 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003310
3311 if (newProgress == 100) {
3312 // onProgressChanged() is called for sub-frame too while
3313 // onPageFinished() is only called for the main frame. sync
3314 // cookie and cache promptly here.
3315 CookieSyncManager.getInstance().sync();
3316 }
3317 }
3318
3319 @Override
3320 public void onReceivedTitle(WebView view, String title) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003321 String url = view.getOriginalUrl();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003322
3323 // here, if url is null, we want to reset the title
3324 setUrlTitle(url, title);
3325
3326 if (url == null ||
3327 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3328 return;
3329 }
3330 if (url.startsWith("http://www.")) {
3331 url = url.substring(11);
3332 } else if (url.startsWith("http://")) {
3333 url = url.substring(4);
3334 }
3335 try {
3336 url = "%" + url;
3337 String [] selArgs = new String[] { url };
3338
3339 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3340 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3341 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3342 Browser.HISTORY_PROJECTION, where, selArgs, null);
3343 if (c.moveToFirst()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003344 if (Config.LOGV) {
3345 Log.v(LOGTAG, "updating cursor");
3346 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003347 // Current implementation of database only has one entry per
3348 // url.
3349 int titleIndex =
3350 c.getColumnIndex(Browser.BookmarkColumns.TITLE);
3351 c.updateString(titleIndex, title);
3352 c.commitUpdates();
3353 }
3354 c.close();
3355 } catch (IllegalStateException e) {
3356 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3357 } catch (SQLiteException ex) {
3358 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3359 }
3360 }
3361
3362 @Override
3363 public void onReceivedIcon(WebView view, Bitmap icon) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003364 updateIcon(view.getUrl(), icon);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003365 }
3366
3367 //----------------------------------------------------------------------
3368 // JavaScript functions.
3369 //----------------------------------------------------------------------
3370
3371 // Show an alert to the user.
3372 @Override
3373 public boolean onJsAlert(WebView view, String url, String message,
3374 JsResult result) {
3375 String title = url;
3376 if (URLUtil.isDataUrl(url)) {
3377 // For data: urls, we just display 'JavaScript' similar to
3378 // Safari.
3379 title = getString(R.string.js_dialog_title_default);
3380 } else {
3381 try {
3382 URL aUrl = new URL(url);
3383 // Example: "The page at 'http://www.mit.edu' says:"
3384 title = getText(R.string.js_dialog_title_prefix)
3385 + " '"
3386 + (aUrl.getProtocol() + "://" + aUrl.getHost())
3387 + "' "
3388 + getText(R.string.js_dialog_title_suffix);
3389 } catch (MalformedURLException ex) {
3390 // do nothing. just use the url passed as the title
3391 }
3392 }
3393 final JsResult res = result;
3394 new AlertDialog.Builder(BrowserActivity.this)
3395 .setTitle(title)
3396 .setMessage(message)
3397 .setPositiveButton(R.string.ok,
3398 new AlertDialog.OnClickListener() {
3399 public void onClick(DialogInterface dialog,
3400 int which) {
3401 res.confirm();
3402 }
3403 })
3404 .setCancelable(false)
3405 .show();
3406 return true;
3407 }
3408
3409 @Override
3410 public boolean onJsConfirm(WebView view, String url, String message,
3411 final JsResult result) {
3412 String title = url;
3413 try {
3414 URL aUrl = new URL(url);
3415 // Example: "The page at 'http://www.mit.edu' says:"
3416 title = getText(R.string.js_dialog_title_prefix)
3417 + " '"
3418 + (aUrl.getProtocol() + "://" + aUrl.getHost())
3419 + "' "
3420 + getText(R.string.js_dialog_title_suffix);
3421 } catch (MalformedURLException ex) {
3422 // do nothing. just use the url passed as the title
3423 }
3424 new AlertDialog.Builder(BrowserActivity.this)
3425 .setTitle(title)
3426 .setMessage(message)
3427 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3428 public void onClick(DialogInterface dialog, int which) {
3429 mHandler.obtainMessage(JS_CONFIRM, 1, 0, result).sendToTarget();
3430 }})
3431 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3432 public void onClick(DialogInterface dialog, int which) {
3433 mHandler.obtainMessage(JS_CONFIRM, 0, 0, result).sendToTarget();
3434 }})
3435 .show();
3436 // Return true so WebView knows we will handle the confirm.
3437 return true;
3438 }
3439
3440 @Override
3441 public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
3442 final JsPromptResult result) {
3443 String title = url;
3444 try {
3445 URL aUrl = new URL(url);
3446 // Example: "The page at 'http://www.mit.edu' says:"
3447 title = getText(R.string.js_dialog_title_prefix)
3448 + " '"
3449 + (aUrl.getProtocol() + "://" + aUrl.getHost())
3450 + "' "
3451 + getText(R.string.js_dialog_title_suffix);
3452 } catch (MalformedURLException ex) {
3453 // do nothing, just use the url passed as the title
3454 }
3455
3456 final LayoutInflater factory = LayoutInflater.from(BrowserActivity.this);
3457 final View v = factory.inflate(R.layout.js_prompt, null);
3458 ((TextView)v.findViewById(R.id.message)).setText(message);
3459 ((EditText)v.findViewById(R.id.value)).setText(defaultValue);
3460
3461 new AlertDialog.Builder(BrowserActivity.this)
3462 .setTitle(title)
3463 .setView(v)
3464 .setPositiveButton(R.string.ok,
3465 new DialogInterface.OnClickListener() {
3466 public void onClick(DialogInterface dialog, int whichButton) {
3467 String value = ((EditText)v.findViewById(R.id.value)).getText()
3468 .toString();
3469 result.confirm(value);
3470 }
3471 })
3472 .setNegativeButton(R.string.cancel,
3473 new DialogInterface.OnClickListener() {
3474 public void onClick(DialogInterface dialog, int whichButton) {
3475 result.cancel();
3476 }
3477 })
3478 .setOnCancelListener(
3479 new DialogInterface.OnCancelListener() {
3480 public void onCancel(DialogInterface dialog) {
3481 result.cancel();
3482 }
3483 })
3484 .show();
3485
3486 // Return true so WebView knows we will handle the prompt.
3487 return true;
3488 }
3489
3490 @Override
3491 public boolean onJsBeforeUnload(WebView view, String url,
3492 String message, final JsResult result) {
3493 final String m =
3494 getString(R.string.js_dialog_before_unload, message);
3495 new AlertDialog.Builder(BrowserActivity.this)
3496 .setMessage(m)
3497 .setPositiveButton(R.string.ok,
3498 new DialogInterface.OnClickListener() {
3499 public void onClick(DialogInterface dialog,
3500 int which) {
3501 // Use JS_CONFIRM since it has the same
3502 // behavior we want here.
3503 mHandler.obtainMessage(JS_CONFIRM, 1, 0,
3504 result).sendToTarget();
3505 }})
3506 .setNegativeButton(R.string.cancel,
3507 new DialogInterface.OnClickListener() {
3508 public void onClick(DialogInterface dialog,
3509 int which) {
3510 // Use JS_CONFIRM since it has the same
3511 // behavior we want here.
3512 mHandler.obtainMessage(JS_CONFIRM, 0, 0,
3513 result).sendToTarget();
3514 }})
3515 .show();
3516 // Return true so WebView knows we will handle the dialog.
3517 return true;
3518 }
3519 };
3520
3521 /**
3522 * Notify the host application a download should be done, or that
3523 * the data should be streamed if a streaming viewer is available.
3524 * @param url The full url to the content that should be downloaded
3525 * @param contentDisposition Content-disposition http header, if
3526 * present.
3527 * @param mimetype The mimetype of the content reported by the server
3528 * @param contentLength The file size reported by the server
3529 */
3530 public void onDownloadStart(String url, String userAgent,
3531 String contentDisposition, String mimetype, long contentLength) {
3532 // if we're dealing wih A/V content that's not explicitly marked
3533 // for download, check if it's streamable.
3534 if (contentDisposition == null
3535 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3536 // query the package manager to see if there's a registered handler
3537 // that matches.
3538 Intent intent = new Intent(Intent.ACTION_VIEW);
3539 intent.setDataAndType(Uri.parse(url), mimetype);
3540 if (getPackageManager().queryIntentActivities(intent,
3541 PackageManager.MATCH_DEFAULT_ONLY).size() != 0) {
3542 // someone knows how to handle this mime type with this scheme, don't download.
3543 try {
3544 startActivity(intent);
3545 return;
3546 } catch (ActivityNotFoundException ex) {
3547 if (Config.LOGD) {
3548 Log.d(LOGTAG, "activity not found for " + mimetype
3549 + " over " + Uri.parse(url).getScheme(), ex);
3550 }
3551 // Best behavior is to fall back to a download in this case
3552 }
3553 }
3554 }
3555 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3556 }
3557
3558 /**
3559 * Notify the host application a download should be done, even if there
3560 * is a streaming viewer available for thise type.
3561 * @param url The full url to the content that should be downloaded
3562 * @param contentDisposition Content-disposition http header, if
3563 * present.
3564 * @param mimetype The mimetype of the content reported by the server
3565 * @param contentLength The file size reported by the server
3566 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08003567 /*package */ void onDownloadStartNoStream(String url, String userAgent,
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003568 String contentDisposition, String mimetype, long contentLength) {
3569
3570 String filename = URLUtil.guessFileName(url,
3571 contentDisposition, mimetype);
3572
3573 // Check to see if we have an SDCard
The Android Open Source Projected217d92008-12-17 18:05:52 -08003574 String status = Environment.getExternalStorageState();
3575 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3576 int title;
3577 String msg;
3578
3579 // Check to see if the SDCard is busy, same as the music app
3580 if (status.equals(Environment.MEDIA_SHARED)) {
3581 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3582 title = R.string.download_sdcard_busy_dlg_title;
3583 } else {
3584 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3585 title = R.string.download_no_sdcard_dlg_title;
3586 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003587
3588 new AlertDialog.Builder(this)
The Android Open Source Projected217d92008-12-17 18:05:52 -08003589 .setTitle(title)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003590 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003591 .setMessage(msg)
3592 .setPositiveButton(R.string.ok, null)
3593 .show();
3594 return;
3595 }
3596
3597 String cookies = CookieManager.getInstance().getCookie(url);
3598
3599 ContentValues values = new ContentValues();
3600 values.put(Downloads.URI, url);
3601 values.put(Downloads.COOKIE_DATA, cookies);
3602 values.put(Downloads.USER_AGENT, userAgent);
3603 values.put(Downloads.NOTIFICATION_PACKAGE,
3604 getPackageName());
3605 values.put(Downloads.NOTIFICATION_CLASS,
3606 BrowserDownloadPage.class.getCanonicalName());
3607 values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3608 values.put(Downloads.MIMETYPE, mimetype);
3609 values.put(Downloads.FILENAME_HINT, filename);
3610 values.put(Downloads.DESCRIPTION, Uri.parse(url).getHost());
3611 if (contentLength > 0) {
3612 values.put(Downloads.TOTAL_BYTES, contentLength);
3613 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08003614 if (mimetype == null) {
3615 // We must have long pressed on a link or image to download it. We
3616 // are not sure of the mimetype in this case, so do a head request
3617 new FetchUrlMimeType(this).execute(values);
3618 } else {
3619 final Uri contentUri =
3620 getContentResolver().insert(Downloads.CONTENT_URI, values);
3621 viewDownloads(contentUri);
3622 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003623
3624 }
3625
3626 /**
3627 * Resets the lock icon. This method is called when we start a new load and
3628 * know the url to be loaded.
3629 */
3630 private void resetLockIcon(String url) {
3631 // Save the lock-icon state (we revert to it if the load gets cancelled)
3632 saveLockIcon();
3633
3634 mLockIconType = LOCK_ICON_UNSECURE;
3635 if (URLUtil.isHttpsUrl(url)) {
3636 mLockIconType = LOCK_ICON_SECURE;
3637 if (Config.LOGV) {
3638 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3639 " reset lock icon to " + mLockIconType);
3640 }
3641 }
3642
3643 updateLockIconImage(LOCK_ICON_UNSECURE);
3644 }
3645
3646 /**
3647 * Resets the lock icon. This method is called when the icon needs to be
3648 * reset but we do not know whether we are loading a secure or not secure
3649 * page.
3650 */
3651 private void resetLockIcon() {
3652 // Save the lock-icon state (we revert to it if the load gets cancelled)
3653 saveLockIcon();
3654
3655 mLockIconType = LOCK_ICON_UNSECURE;
3656
3657 if (Config.LOGV) {
3658 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3659 " reset lock icon to " + mLockIconType);
3660 }
3661
3662 updateLockIconImage(LOCK_ICON_UNSECURE);
3663 }
3664
3665 /**
3666 * Updates the lock-icon image in the title-bar.
3667 */
3668 private void updateLockIconImage(int lockIconType) {
3669 Drawable d = null;
3670 if (lockIconType == LOCK_ICON_SECURE) {
3671 d = mSecLockIcon;
3672 } else if (lockIconType == LOCK_ICON_MIXED) {
3673 d = mMixLockIcon;
3674 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08003675 // If the tab overview is animating or being shown, do not update the
3676 // lock icon.
3677 if (mAnimationCount == 0 && mTabOverview == null) {
3678 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
3679 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003680 }
3681
3682 /**
3683 * Displays a page-info dialog.
The Android Open Source Projected217d92008-12-17 18:05:52 -08003684 * @param tab The tab to show info about
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003685 * @param fromShowSSLCertificateOnError The flag that indicates whether
3686 * this dialog was opened from the SSL-certificate-on-error dialog or
3687 * not. This is important, since we need to know whether to return to
3688 * the parent dialog or simply dismiss.
3689 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08003690 private void showPageInfo(final TabControl.Tab tab,
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003691 final boolean fromShowSSLCertificateOnError) {
3692 final LayoutInflater factory = LayoutInflater
3693 .from(this);
3694
3695 final View pageInfoView = factory.inflate(R.layout.page_info, null);
The Android Open Source Projected217d92008-12-17 18:05:52 -08003696
3697 final WebView view = tab.getWebView();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003698
3699 String url = null;
3700 String title = null;
3701
The Android Open Source Projected217d92008-12-17 18:05:52 -08003702 if (view == null) {
3703 url = tab.getUrl();
3704 title = tab.getTitle();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003705 } else if (view == mTabControl.getCurrentWebView()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003706 // Use the cached title and url if this is the current WebView
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003707 url = mUrl;
3708 title = mTitle;
3709 } else {
3710 url = view.getUrl();
3711 title = view.getTitle();
3712 }
3713
3714 if (url == null) {
3715 url = "";
3716 }
3717 if (title == null) {
3718 title = "";
3719 }
3720
3721 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3722 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3723
The Android Open Source Projected217d92008-12-17 18:05:52 -08003724 mPageInfoView = tab;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003725 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3726
3727 AlertDialog.Builder alertDialogBuilder =
3728 new AlertDialog.Builder(this)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003729 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003730 .setView(pageInfoView)
3731 .setPositiveButton(
3732 R.string.ok,
3733 new DialogInterface.OnClickListener() {
3734 public void onClick(DialogInterface dialog,
3735 int whichButton) {
3736 mPageInfoDialog = null;
3737 mPageInfoView = null;
3738 mPageInfoFromShowSSLCertificateOnError = null;
3739
3740 // if we came here from the SSL error dialog
3741 if (fromShowSSLCertificateOnError) {
3742 // go back to the SSL error dialog
3743 showSSLCertificateOnError(
3744 mSSLCertificateOnErrorView,
3745 mSSLCertificateOnErrorHandler,
3746 mSSLCertificateOnErrorError);
3747 }
3748 }
3749 })
3750 .setOnCancelListener(
3751 new DialogInterface.OnCancelListener() {
3752 public void onCancel(DialogInterface dialog) {
3753 mPageInfoDialog = null;
3754 mPageInfoView = null;
3755 mPageInfoFromShowSSLCertificateOnError = null;
3756
3757 // if we came here from the SSL error dialog
3758 if (fromShowSSLCertificateOnError) {
3759 // go back to the SSL error dialog
3760 showSSLCertificateOnError(
3761 mSSLCertificateOnErrorView,
3762 mSSLCertificateOnErrorHandler,
3763 mSSLCertificateOnErrorError);
3764 }
3765 }
3766 });
3767
3768 // if we have a main top-level page SSL certificate set or a certificate
3769 // error
The Android Open Source Projected217d92008-12-17 18:05:52 -08003770 if (fromShowSSLCertificateOnError ||
3771 (view != null && view.getCertificate() != null)) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003772 // add a 'View Certificate' button
3773 alertDialogBuilder.setNeutralButton(
3774 R.string.view_certificate,
3775 new DialogInterface.OnClickListener() {
3776 public void onClick(DialogInterface dialog,
3777 int whichButton) {
3778 mPageInfoDialog = null;
3779 mPageInfoView = null;
3780 mPageInfoFromShowSSLCertificateOnError = null;
3781
3782 // if we came here from the SSL error dialog
3783 if (fromShowSSLCertificateOnError) {
3784 // go back to the SSL error dialog
3785 showSSLCertificateOnError(
3786 mSSLCertificateOnErrorView,
3787 mSSLCertificateOnErrorHandler,
3788 mSSLCertificateOnErrorError);
3789 } else {
3790 // otherwise, display the top-most certificate from
3791 // the chain
3792 if (view.getCertificate() != null) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003793 showSSLCertificate(tab);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003794 }
3795 }
3796 }
3797 });
3798 }
3799
3800 mPageInfoDialog = alertDialogBuilder.show();
3801 }
3802
3803 /**
3804 * Displays the main top-level page SSL certificate dialog
3805 * (accessible from the Page-Info dialog).
The Android Open Source Projected217d92008-12-17 18:05:52 -08003806 * @param tab The tab to show certificate for.
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003807 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08003808 private void showSSLCertificate(final TabControl.Tab tab) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003809 final View certificateView =
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003810 inflateCertificateView(tab.getWebView().getCertificate());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003811 if (certificateView == null) {
3812 return;
3813 }
3814
3815 LayoutInflater factory = LayoutInflater.from(this);
3816
3817 final LinearLayout placeholder =
3818 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3819
3820 LinearLayout ll = (LinearLayout) factory.inflate(
3821 R.layout.ssl_success, placeholder);
3822 ((TextView)ll.findViewById(R.id.success))
3823 .setText(R.string.ssl_certificate_is_valid);
3824
The Android Open Source Projected217d92008-12-17 18:05:52 -08003825 mSSLCertificateView = tab;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003826 mSSLCertificateDialog =
3827 new AlertDialog.Builder(this)
3828 .setTitle(R.string.ssl_certificate).setIcon(
3829 R.drawable.ic_dialog_browser_certificate_secure)
3830 .setView(certificateView)
3831 .setPositiveButton(R.string.ok,
3832 new DialogInterface.OnClickListener() {
3833 public void onClick(DialogInterface dialog,
3834 int whichButton) {
3835 mSSLCertificateDialog = null;
3836 mSSLCertificateView = null;
3837
The Android Open Source Projected217d92008-12-17 18:05:52 -08003838 showPageInfo(tab, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003839 }
3840 })
3841 .setOnCancelListener(
3842 new DialogInterface.OnCancelListener() {
3843 public void onCancel(DialogInterface dialog) {
3844 mSSLCertificateDialog = null;
3845 mSSLCertificateView = null;
3846
The Android Open Source Projected217d92008-12-17 18:05:52 -08003847 showPageInfo(tab, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003848 }
3849 })
3850 .show();
3851 }
3852
3853 /**
3854 * Displays the SSL error certificate dialog.
3855 * @param view The target web-view.
3856 * @param handler The SSL error handler responsible for cancelling the
3857 * connection that resulted in an SSL error or proceeding per user request.
3858 * @param error The SSL error object.
3859 */
3860 private void showSSLCertificateOnError(
3861 final WebView view, final SslErrorHandler handler, final SslError error) {
3862
3863 final View certificateView =
3864 inflateCertificateView(error.getCertificate());
3865 if (certificateView == null) {
3866 return;
3867 }
3868
3869 LayoutInflater factory = LayoutInflater.from(this);
3870
3871 final LinearLayout placeholder =
3872 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3873
3874 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3875 LinearLayout ll = (LinearLayout)factory
3876 .inflate(R.layout.ssl_warning, placeholder);
3877 ((TextView)ll.findViewById(R.id.warning))
3878 .setText(R.string.ssl_untrusted);
3879 }
3880
3881 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3882 LinearLayout ll = (LinearLayout)factory
3883 .inflate(R.layout.ssl_warning, placeholder);
3884 ((TextView)ll.findViewById(R.id.warning))
3885 .setText(R.string.ssl_mismatch);
3886 }
3887
3888 if (error.hasError(SslError.SSL_EXPIRED)) {
3889 LinearLayout ll = (LinearLayout)factory
3890 .inflate(R.layout.ssl_warning, placeholder);
3891 ((TextView)ll.findViewById(R.id.warning))
3892 .setText(R.string.ssl_expired);
3893 }
3894
3895 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3896 LinearLayout ll = (LinearLayout)factory
3897 .inflate(R.layout.ssl_warning, placeholder);
3898 ((TextView)ll.findViewById(R.id.warning))
3899 .setText(R.string.ssl_not_yet_valid);
3900 }
3901
3902 mSSLCertificateOnErrorHandler = handler;
3903 mSSLCertificateOnErrorView = view;
3904 mSSLCertificateOnErrorError = error;
3905 mSSLCertificateOnErrorDialog =
3906 new AlertDialog.Builder(this)
3907 .setTitle(R.string.ssl_certificate).setIcon(
3908 R.drawable.ic_dialog_browser_certificate_partially_secure)
3909 .setView(certificateView)
3910 .setPositiveButton(R.string.ok,
3911 new DialogInterface.OnClickListener() {
3912 public void onClick(DialogInterface dialog,
3913 int whichButton) {
3914 mSSLCertificateOnErrorDialog = null;
3915 mSSLCertificateOnErrorView = null;
3916 mSSLCertificateOnErrorHandler = null;
3917 mSSLCertificateOnErrorError = null;
3918
3919 mWebViewClient.onReceivedSslError(
3920 view, handler, error);
3921 }
3922 })
3923 .setNeutralButton(R.string.page_info_view,
3924 new DialogInterface.OnClickListener() {
3925 public void onClick(DialogInterface dialog,
3926 int whichButton) {
3927 mSSLCertificateOnErrorDialog = null;
3928
3929 // do not clear the dialog state: we will
3930 // need to show the dialog again once the
3931 // user is done exploring the page-info details
3932
The Android Open Source Projected217d92008-12-17 18:05:52 -08003933 showPageInfo(mTabControl.getTabFromView(view),
3934 true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003935 }
3936 })
3937 .setOnCancelListener(
3938 new DialogInterface.OnCancelListener() {
3939 public void onCancel(DialogInterface dialog) {
3940 mSSLCertificateOnErrorDialog = null;
3941 mSSLCertificateOnErrorView = null;
3942 mSSLCertificateOnErrorHandler = null;
3943 mSSLCertificateOnErrorError = null;
3944
3945 mWebViewClient.onReceivedSslError(
3946 view, handler, error);
3947 }
3948 })
3949 .show();
3950 }
3951
3952 /**
3953 * Inflates the SSL certificate view (helper method).
3954 * @param certificate The SSL certificate.
3955 * @return The resultant certificate view with issued-to, issued-by,
3956 * issued-on, expires-on, and possibly other fields set.
3957 * If the input certificate is null, returns null.
3958 */
3959 private View inflateCertificateView(SslCertificate certificate) {
3960 if (certificate == null) {
3961 return null;
3962 }
3963
3964 LayoutInflater factory = LayoutInflater.from(this);
3965
3966 View certificateView = factory.inflate(
3967 R.layout.ssl_certificate, null);
3968
3969 // issued to:
3970 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3971 if (issuedTo != null) {
3972 ((TextView) certificateView.findViewById(R.id.to_common))
3973 .setText(issuedTo.getCName());
3974 ((TextView) certificateView.findViewById(R.id.to_org))
3975 .setText(issuedTo.getOName());
3976 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3977 .setText(issuedTo.getUName());
3978 }
3979
3980 // issued by:
3981 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3982 if (issuedBy != null) {
3983 ((TextView) certificateView.findViewById(R.id.by_common))
3984 .setText(issuedBy.getCName());
3985 ((TextView) certificateView.findViewById(R.id.by_org))
3986 .setText(issuedBy.getOName());
3987 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3988 .setText(issuedBy.getUName());
3989 }
3990
3991 // issued on:
3992 String issuedOn = reformatCertificateDate(
3993 certificate.getValidNotBefore());
3994 ((TextView) certificateView.findViewById(R.id.issued_on))
3995 .setText(issuedOn);
3996
3997 // expires on:
3998 String expiresOn = reformatCertificateDate(
3999 certificate.getValidNotAfter());
4000 ((TextView) certificateView.findViewById(R.id.expires_on))
4001 .setText(expiresOn);
4002
4003 return certificateView;
4004 }
4005
4006 /**
4007 * Re-formats the certificate date (Date.toString()) string to
4008 * a properly localized date string.
4009 * @return Properly localized version of the certificate date string and
4010 * the original certificate date string if fails to localize.
4011 * If the original string is null, returns an empty string "".
4012 */
4013 private String reformatCertificateDate(String certificateDate) {
4014 String reformattedDate = null;
4015
4016 if (certificateDate != null) {
4017 Date date = null;
4018 try {
4019 date = java.text.DateFormat.getInstance().parse(certificateDate);
4020 } catch (ParseException e) {
4021 date = null;
4022 }
4023
4024 if (date != null) {
4025 reformattedDate =
4026 DateFormat.getDateFormat(this).format(date);
4027 }
4028 }
4029
4030 return reformattedDate != null ? reformattedDate :
4031 (certificateDate != null ? certificateDate : "");
4032 }
4033
4034 /**
4035 * Displays an http-authentication dialog.
4036 */
4037 private void showHttpAuthentication(final HttpAuthHandler handler,
4038 final String host, final String realm, final String title,
4039 final String name, final String password, int focusId) {
4040 LayoutInflater factory = LayoutInflater.from(this);
4041 final View v = factory
4042 .inflate(R.layout.http_authentication, null);
4043 if (name != null) {
4044 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4045 }
4046 if (password != null) {
4047 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4048 }
4049
4050 String titleText = title;
4051 if (titleText == null) {
4052 titleText = getText(R.string.sign_in_to).toString().replace(
4053 "%s1", host).replace("%s2", realm);
4054 }
4055
4056 mHttpAuthHandler = handler;
4057 mHttpAuthenticationDialog = new AlertDialog.Builder(this)
4058 .setTitle(titleText)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004059 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004060 .setView(v)
4061 .setPositiveButton(R.string.action,
4062 new DialogInterface.OnClickListener() {
4063 public void onClick(DialogInterface dialog,
4064 int whichButton) {
4065 String nm = ((EditText) v
4066 .findViewById(R.id.username_edit))
4067 .getText().toString();
4068 String pw = ((EditText) v
4069 .findViewById(R.id.password_edit))
4070 .getText().toString();
4071 BrowserActivity.this.setHttpAuthUsernamePassword
4072 (host, realm, nm, pw);
4073 handler.proceed(nm, pw);
4074 mHttpAuthenticationDialog = null;
4075 mHttpAuthHandler = null;
4076 }})
4077 .setNegativeButton(R.string.cancel,
4078 new DialogInterface.OnClickListener() {
4079 public void onClick(DialogInterface dialog,
4080 int whichButton) {
4081 handler.cancel();
4082 BrowserActivity.this.resetTitleAndRevertLockIcon();
4083 mHttpAuthenticationDialog = null;
4084 mHttpAuthHandler = null;
4085 }})
4086 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4087 public void onCancel(DialogInterface dialog) {
4088 handler.cancel();
4089 BrowserActivity.this.resetTitleAndRevertLockIcon();
4090 mHttpAuthenticationDialog = null;
4091 mHttpAuthHandler = null;
4092 }})
4093 .show();
4094 if (focusId != 0) {
4095 mHttpAuthenticationDialog.findViewById(focusId).requestFocus();
4096 } else {
4097 v.findViewById(R.id.username_edit).requestFocus();
4098 }
4099 }
4100
4101 public int getProgress() {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004102 WebView w = mTabControl.getCurrentWebView();
4103 if (w != null) {
4104 return w.getProgress();
4105 } else {
4106 return 100;
4107 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004108 }
4109
4110 /**
4111 * Set HTTP authentication password.
4112 *
4113 * @param host The host for the password
4114 * @param realm The realm for the password
4115 * @param username The username for the password. If it is null, it means
4116 * password can't be saved.
4117 * @param password The password
4118 */
4119 public void setHttpAuthUsernamePassword(String host, String realm,
4120 String username,
4121 String password) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004122 WebView w = mTabControl.getCurrentWebView();
4123 if (w != null) {
4124 w.setHttpAuthUsernamePassword(host, realm, username, password);
4125 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004126 }
4127
4128 /**
4129 * http stack says net has come or gone... inform the user
4130 * @param up true if net has come up, false if net has gone down
4131 */
4132 public void onNetworkToggle(boolean up) {
4133 if (up) {
4134 if (mAlertDialog != null) {
4135 mAlertDialog.cancel();
4136 mAlertDialog = null;
4137 }
4138 } else {
4139 if (mInLoad && mAlertDialog == null) {
4140 mAlertDialog = new AlertDialog.Builder(this)
4141 .setTitle(R.string.loadSuspendedTitle)
4142 .setMessage(R.string.loadSuspended)
4143 .setPositiveButton(R.string.ok, null)
4144 .show();
4145 }
4146 }
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004147 WebView w = mTabControl.getCurrentWebView();
4148 if (w != null) {
4149 w.setNetworkAvailable(up);
4150 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004151 }
4152
4153 @Override
4154 protected void onActivityResult(int requestCode, int resultCode,
4155 Intent intent) {
4156 switch (requestCode) {
4157 case BOOKMARKS_PAGE:
4158 case CLASSIC_HISTORY_PAGE:
4159 if (resultCode == RESULT_OK && intent != null) {
4160 String data = intent.getAction();
4161 Bundle extras = intent.getExtras();
4162 if (extras != null && extras.getBoolean("new_window", false)) {
4163 openTab(data);
4164 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004165 final TabControl.Tab currentTab =
4166 mTabControl.getCurrentTab();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004167 // If the Window overview is up and we are not in the
4168 // middle of an animation, animate away from it to the
4169 // current tab.
4170 if (mTabOverview != null && mAnimationCount == 0) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004171 sendAnimateFromOverview(currentTab, false, data,
4172 TAB_OVERVIEW_DELAY, null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004173 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004174 dismissSubWindow(currentTab);
4175 if (data != null && data.length() != 0) {
4176 getTopWindow().loadUrl(data);
4177 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004178 }
4179 }
4180 }
4181 break;
4182 default:
4183 break;
4184 }
4185 getTopWindow().requestFocus();
4186 }
4187
4188 /*
4189 * This method is called as a result of the user selecting the options
4190 * menu to see the download window, or when a download changes state. It
4191 * shows the download window ontop of the current window.
4192 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08004193 /* package */ void viewDownloads(Uri downloadRecord) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004194 Intent intent = new Intent(this,
4195 BrowserDownloadPage.class);
4196 intent.setData(downloadRecord);
4197 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4198
4199 }
4200
4201 /**
4202 * Handle results from Tab Switcher mTabOverview tool
4203 */
4204 private class TabListener implements ImageGrid.Listener {
4205 public void remove(int position) {
4206 // Note: Remove is not enabled if we have only one tab.
4207 if (Config.DEBUG && mTabControl.getTabCount() == 1) {
4208 throw new AssertionError();
4209 }
4210
The Android Open Source Projected217d92008-12-17 18:05:52 -08004211 // Remember the current tab.
4212 TabControl.Tab current = mTabControl.getCurrentTab();
4213 final TabControl.Tab remove = mTabControl.getTab(position);
4214 mTabControl.removeTab(remove);
4215 // If we removed the current tab, use the tab at position - 1 if
4216 // possible.
4217 if (current == remove) {
4218 // If the user removes the last tab, act like the New Tab item
4219 // was clicked on.
4220 if (mTabControl.getTabCount() == 0) {
4221 current = mTabControl.createNewTab(false);
4222 sendAnimateFromOverview(current, true,
4223 mSettings.getHomePage(), TAB_OVERVIEW_DELAY, null);
4224 } else {
4225 final int index = position > 0 ? (position - 1) : 0;
4226 current = mTabControl.getTab(index);
4227 }
4228 }
4229
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004230 // The tab overview could have been dismissed before this method is
4231 // called.
4232 if (mTabOverview != null) {
4233 // Remove the tab and change the index.
The Android Open Source Projected217d92008-12-17 18:05:52 -08004234 mTabOverview.remove(position);
4235 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004236 }
4237
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004238 // Only the current tab ensures its WebView is non-null. This
4239 // implies that we are reloading the freed tab.
The Android Open Source Projected217d92008-12-17 18:05:52 -08004240 mTabControl.setCurrentTab(current);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004241 }
4242 public void onClick(int index) {
4243 // Change the tab if necessary.
4244 // Index equals ImageGrid.CANCEL when pressing back from the tab
4245 // overview.
4246 if (index == ImageGrid.CANCEL) {
4247 index = mTabControl.getCurrentIndex();
4248 // The current index is -1 if the current tab was removed.
4249 if (index == -1) {
4250 // Take the last tab as a fallback.
4251 index = mTabControl.getTabCount() - 1;
4252 }
4253 }
4254
4255 // Clear all the data for tab picker so next time it will be
4256 // recreated.
4257 mTabControl.wipeAllPickerData();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004258
4259 // NEW_TAB means that the "New Tab" cell was clicked on.
4260 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004261 openTabAndShow(mSettings.getHomePage(), null, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004262 } else {
4263 sendAnimateFromOverview(mTabControl.getTab(index),
4264 false, null, 0, null);
4265 }
4266 }
4267 }
4268
4269 // A fake View that draws the WebView's picture with a fast zoom filter.
4270 // The View is used in case the tab is freed during the animation because
4271 // of low memory.
4272 private static class AnimatingView extends View {
4273 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4274 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4275 private static final DrawFilter sZoomFilter =
4276 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4277 private final Picture mPicture;
4278 private final float mScale;
4279 private final int mScrollX;
4280 private final int mScrollY;
4281 final TabControl.Tab mTab;
4282
4283 AnimatingView(Context ctxt, TabControl.Tab t) {
4284 super(ctxt);
4285 mTab = t;
4286 // Use the top window in the animation since the tab overview will
4287 // display the top window in each cell.
4288 final WebView w = t.getTopWindow();
4289 mPicture = w.capturePicture();
4290 mScale = w.getScale() / w.getWidth();
4291 mScrollX = w.getScrollX();
4292 mScrollY = w.getScrollY();
4293 }
4294
4295 @Override
4296 protected void onDraw(Canvas canvas) {
4297 canvas.save();
4298 canvas.drawColor(Color.WHITE);
The Android Open Source Projected217d92008-12-17 18:05:52 -08004299 if (mPicture != null) {
4300 canvas.setDrawFilter(sZoomFilter);
4301 float scale = getWidth() * mScale;
4302 canvas.scale(scale, scale);
4303 canvas.translate(-mScrollX, -mScrollY);
4304 canvas.drawPicture(mPicture);
4305 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004306 canvas.restore();
4307 }
4308 }
4309
4310 /**
4311 * Open the tab picker. This function will always use the current tab in
4312 * its animation.
4313 * @param stay boolean stating whether the tab picker is to remain open
4314 * (in which case it needs a listener and its menu) or not.
4315 * @param index The index of the tab to show as the selection in the tab
4316 * overview.
4317 * @param remove If true, the tab at index will be removed after the
4318 * animation completes.
4319 */
4320 private void tabPicker(final boolean stay, final int index,
4321 final boolean remove) {
4322 if (mTabOverview != null) {
4323 return;
4324 }
4325
4326 int size = mTabControl.getTabCount();
4327
4328 TabListener l = null;
4329 if (stay) {
4330 l = mTabListener = new TabListener();
4331 }
4332 mTabOverview = new ImageGrid(this, stay, l);
4333
4334 for (int i = 0; i < size; i++) {
4335 final TabControl.Tab t = mTabControl.getTab(i);
4336 mTabControl.populatePickerData(t);
4337 mTabOverview.add(t);
4338 }
4339
4340 // Tell the tab overview to show the current tab, the tab overview will
4341 // handle the "New Tab" case.
4342 int currentIndex = mTabControl.getCurrentIndex();
4343 mTabOverview.setCurrentIndex(currentIndex);
4344
4345 // Attach the tab overview.
4346 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4347
4348 // Create a fake AnimatingView to animate the WebView's picture.
4349 final TabControl.Tab current = mTabControl.getCurrentTab();
4350 final AnimatingView v = new AnimatingView(this, current);
4351 mContentView.addView(v, COVER_SCREEN_PARAMS);
4352 removeTabFromContentView(current);
4353 // Pause timers to get the animation smoother.
4354 current.getWebView().pauseTimers();
4355
4356 // Send a message so the tab picker has a chance to layout and get
4357 // positions for all the cells.
4358 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4359 index, remove ? 1 : 0, v));
4360 // Setting this will indicate that we are animating to the overview. We
4361 // set it here to prevent another request to animate from coming in
4362 // between now and when ANIMATE_TO_OVERVIEW is handled.
4363 mAnimationCount++;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004364 // Always change the title bar to the window overview title while
4365 // animating.
4366 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4367 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4368 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4369 Window.PROGRESS_VISIBILITY_OFF);
4370 setTitle(R.string.tab_picker_title);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004371 // Make the menu empty until the animation completes.
4372 mMenuState = EMPTY_MENU;
4373 }
4374
4375 private void bookmarksPicker() {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004376 WebView current = mTabControl.getCurrentWebView();
4377 if (current == null) {
4378 return;
4379 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004380 Intent intent = new Intent(this,
4381 BrowserBookmarksPage.class);
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004382 String title = current.getTitle();
4383 String url = current.getUrl();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004384 // Just in case the user opens bookmarks before a page finishes loading
4385 // so the current history item, and therefore the page, is null.
4386 if (null == url) {
4387 url = mLastEnteredUrl;
4388 // This can happen.
4389 if (null == url) {
4390 url = mSettings.getHomePage();
4391 }
4392 }
4393 // In case the web page has not yet received its associated title.
4394 if (title == null) {
4395 title = url;
4396 }
4397 intent.putExtra("title", title);
4398 intent.putExtra("url", url);
4399 intent.putExtra("maxTabsOpen",
4400 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4401 startActivityForResult(intent, BOOKMARKS_PAGE);
4402 }
4403
The Android Open Source Projected217d92008-12-17 18:05:52 -08004404 // Called when loading from context menu or LOAD_URL message
4405 private void loadURL(WebView view, String url) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004406 // In case the user enters nothing.
The Android Open Source Projected217d92008-12-17 18:05:52 -08004407 if (url != null && url.length() != 0 && view != null) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004408 url = smartUrlFilter(url);
The Android Open Source Projected217d92008-12-17 18:05:52 -08004409 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4410 view.loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004411 }
4412 }
4413 }
4414
4415 private void checkMemory() {
4416 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4417 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4418 .getMemoryInfo(mi);
4419 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4420 // mi.threshold) for now
4421 // if (mi.lowMemory) {
4422 if (mi.availMem < mi.threshold) {
4423 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4424 + (mi.availMem / 1024) + "K threshold="
4425 + (mi.threshold / 1024) + "K");
4426 mTabControl.freeMemory();
4427 }
4428 }
4429
4430 private String smartUrlFilter(Uri inUri) {
4431 if (inUri != null) {
4432 return smartUrlFilter(inUri.toString());
4433 }
4434 return null;
4435 }
4436
4437
4438 // get window count
4439
4440 int getWindowCount(){
4441 if(mTabControl != null){
4442 return mTabControl.getTabCount();
4443 }
4444 return 0;
4445 }
4446
4447 static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4448 "(?i)" + // switch on case insensitive matching
4449 "(" + // begin group for schema
4450 "(?:http|https|file):\\/\\/" +
4451 "|(?:data|about|content|javascript):" +
4452 ")" +
4453 "(.*)" );
4454
4455 /**
4456 * Attempts to determine whether user input is a URL or search
4457 * terms. Anything with a space is passed to search.
4458 *
4459 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4460 * "Http://" converts to "http://"
4461 *
4462 * @return Original or modified URL
4463 *
4464 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08004465 String smartUrlFilter(String url) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004466
The Android Open Source Projected217d92008-12-17 18:05:52 -08004467 String inUrl = url.trim();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004468 boolean hasSpace = inUrl.indexOf(' ') != -1;
4469
The Android Open Source Projected217d92008-12-17 18:05:52 -08004470 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4471 if (matcher.matches()) {
4472 if (hasSpace) {
4473 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004474 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08004475 // force scheme to lowercase
4476 String scheme = matcher.group(1);
4477 String lcScheme = scheme.toLowerCase();
4478 if (!lcScheme.equals(scheme)) {
4479 return lcScheme + matcher.group(2);
4480 }
4481 return inUrl;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004482 }
4483 if (hasSpace) {
4484 // FIXME: quick search, need to be customized by setting
4485 if (inUrl.length() > 2 && inUrl.charAt(1) == ' ') {
4486 // FIXME: Is this the correct place to add to searches?
4487 // what if someone else calls this function?
4488 char char0 = inUrl.charAt(0);
4489
4490 if (char0 == 'g') {
4491 Browser.addSearchUrl(mResolver, inUrl);
4492 return composeSearchUrl(inUrl.substring(2));
4493
4494 } else if (char0 == 'w') {
4495 Browser.addSearchUrl(mResolver, inUrl);
4496 return URLUtil.composeSearchUrl(inUrl.substring(2),
4497 QuickSearch_W,
4498 QUERY_PLACE_HOLDER);
4499
4500 } else if (char0 == 'd') {
4501 Browser.addSearchUrl(mResolver, inUrl);
4502 return URLUtil.composeSearchUrl(inUrl.substring(2),
4503 QuickSearch_D,
4504 QUERY_PLACE_HOLDER);
4505
4506 } else if (char0 == 'l') {
4507 Browser.addSearchUrl(mResolver, inUrl);
4508 // FIXME: we need location in this case
4509 return URLUtil.composeSearchUrl(inUrl.substring(2),
4510 QuickSearch_L,
4511 QUERY_PLACE_HOLDER);
4512 }
4513 }
4514 } else {
4515 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4516 return URLUtil.guessUrl(inUrl);
4517 }
4518 }
4519
4520 Browser.addSearchUrl(mResolver, inUrl);
4521 return composeSearchUrl(inUrl);
4522 }
4523
4524 /* package */static String composeSearchUrl(String search) {
4525 return URLUtil.composeSearchUrl(search, QuickSearch_G,
4526 QUERY_PLACE_HOLDER);
4527 }
4528
The Android Open Source Projected217d92008-12-17 18:05:52 -08004529 /* package */void setBaseSearchUrl(String url) {
4530 if (url == null || url.length() == 0) {
4531 /*
4532 * get the google search url based on the SIM. Default is US. NOTE:
4533 * This code uses resources to optionally select the search Uri,
4534 * based on the MCC value from the SIM. The default string will most
4535 * likely be fine. It is parameterized to accept info from the
4536 * Locale, the language code is the first parameter (%1$s) and the
4537 * country code is the second (%2$s). This code must function in the
4538 * same way as a similar lookup in
4539 * com.android.googlesearch.SuggestionProvider#onCreate(). If you
4540 * change either of these functions, change them both. (The same is
4541 * true for the underlying resource strings, which are stored in
4542 * mcc-specific xml files.)
4543 */
4544 Locale l = Locale.getDefault();
4545 QuickSearch_G = getResources().getString(
4546 R.string.google_search_base, l.getLanguage(),
4547 l.getCountry().toLowerCase())
4548 + "client=ms-"
4549 + SystemProperties.get("ro.com.google.clientid", "unknown")
4550 + "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&q=%s";
4551 } else {
4552 QuickSearch_G = url;
4553 }
4554 }
4555
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004556 private final static int LOCK_ICON_UNSECURE = 0;
4557 private final static int LOCK_ICON_SECURE = 1;
4558 private final static int LOCK_ICON_MIXED = 2;
4559
4560 private int mLockIconType = LOCK_ICON_UNSECURE;
4561 private int mPrevLockType = LOCK_ICON_UNSECURE;
4562
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004563 private BrowserSettings mSettings;
4564 private TabControl mTabControl;
4565 private ContentResolver mResolver;
4566 private FrameLayout mContentView;
4567 private ImageGrid mTabOverview;
4568
4569 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4570 // view, we should rewrite this.
4571 private int mCurrentMenuState = 0;
4572 private int mMenuState = R.id.MAIN_MENU;
4573 private static final int EMPTY_MENU = -1;
4574 private Menu mMenu;
4575
4576 private FindDialog mFindDialog;
4577 // Used to prevent chording to result in firing two shortcuts immediately
4578 // one after another. Fixes bug 1211714.
4579 boolean mCanChord;
4580
4581 private boolean mInLoad;
4582
4583 private boolean mPageStarted;
4584 private boolean mActivityInPause = true;
4585
4586 private boolean mMenuIsDown;
4587
4588 private final KeyTracker mKeyTracker = new KeyTracker(this);
4589
4590 // As trackball doesn't send repeat down, we have to track it ourselves
4591 private boolean mTrackTrackball;
4592
4593 private static boolean mInTrace;
4594
4595 // Performance probe
4596 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4597 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4598 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4599 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4600 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4601 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4602 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4603 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4604 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4605 };
4606
4607 private long mStart;
4608 private long mProcessStart;
4609 private long mUserStart;
4610 private long mSystemStart;
4611 private long mIdleStart;
4612 private long mIrqStart;
4613
4614 private long mUiStart;
4615
4616 private Drawable mMixLockIcon;
4617 private Drawable mSecLockIcon;
4618 private Drawable mGenericFavicon;
4619
4620 /* hold a ref so we can auto-cancel if necessary */
4621 private AlertDialog mAlertDialog;
4622
4623 // Wait for credentials before loading google.com
4624 private ProgressDialog mCredsDlg;
4625
4626 // The up-to-date URL and title (these can be different from those stored
4627 // in WebView, since it takes some time for the information in WebView to
4628 // get updated)
4629 private String mUrl;
4630 private String mTitle;
4631
4632 // As PageInfo has different style for landscape / portrait, we have
4633 // to re-open it when configuration changed
4634 private AlertDialog mPageInfoDialog;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004635 private TabControl.Tab mPageInfoView;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004636 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4637 // dialog, we should not just dismiss it, but should get back to the
4638 // SSL-certificate-on-error dialog. This flag is used to store this state
4639 private Boolean mPageInfoFromShowSSLCertificateOnError;
4640
4641 // as SSLCertificateOnError has different style for landscape / portrait,
4642 // we have to re-open it when configuration changed
4643 private AlertDialog mSSLCertificateOnErrorDialog;
4644 private WebView mSSLCertificateOnErrorView;
4645 private SslErrorHandler mSSLCertificateOnErrorHandler;
4646 private SslError mSSLCertificateOnErrorError;
4647
4648 // as SSLCertificate has different style for landscape / portrait, we
4649 // have to re-open it when configuration changed
4650 private AlertDialog mSSLCertificateDialog;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004651 private TabControl.Tab mSSLCertificateView;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004652
4653 // as HttpAuthentication has different style for landscape / portrait, we
4654 // have to re-open it when configuration changed
4655 private AlertDialog mHttpAuthenticationDialog;
4656 private HttpAuthHandler mHttpAuthHandler;
4657
4658 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4659 new FrameLayout.LayoutParams(
4660 ViewGroup.LayoutParams.FILL_PARENT,
4661 ViewGroup.LayoutParams.FILL_PARENT);
4662 // We may provide UI to customize these
4663 // Google search from the browser
The Android Open Source Projected217d92008-12-17 18:05:52 -08004664 static String QuickSearch_G;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004665 // Wikipedia search
4666 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4667 // Dictionary search
4668 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4669 // Google Mobile Local search
4670 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4671
The Android Open Source Projected217d92008-12-17 18:05:52 -08004672 final static String QUERY_PLACE_HOLDER = "%s";
4673
4674 // "source" parameter for Google search through search key
4675 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4676 // "source" parameter for Google search through search menu
4677 final static String GOOGLE_SEARCH_SOURCE_SEARCHMENU = "browser-menu";
4678 // "source" parameter for Google search through goto menu
4679 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4680 // "source" parameter for Google search through simplily type
4681 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4682 // "source" parameter for Google search suggested by the browser
4683 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4684 // "source" parameter for Google search from unknown source
4685 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004686
4687 private final static String LOGTAG = "browser";
4688
4689 private TabListener mTabListener;
4690
4691 private String mLastEnteredUrl;
4692
4693 private PowerManager.WakeLock mWakeLock;
4694 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4695
4696 private Toast mStopToast;
4697
4698 // Used during animations to prevent other animations from being triggered.
4699 // A count is used since the animation to and from the Window overview can
4700 // overlap. A count of 0 means no animation where a count of > 0 means
4701 // there are animations in progress.
4702 private int mAnimationCount;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004703
4704 // As the ids are dynamically created, we can't guarantee that they will
4705 // be in sequence, so this static array maps ids to a window number.
4706 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4707 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4708 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4709 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004710
4711 // monitor platform changes
4712 private IntentFilter mNetworkStateChangedFilter;
4713 private BroadcastReceiver mNetworkStateIntentReceiver;
4714
4715 // activity requestCode
4716 final static int BOOKMARKS_PAGE = 1;
4717 final static int CLASSIC_HISTORY_PAGE = 2;
4718 final static int DOWNLOAD_PAGE = 3;
4719 final static int PREFERENCES_PAGE = 4;
4720
4721 // the frenquency of checking whether system memory is low
4722 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
4723}