blob: 71fef381dfefe8186c86a319fec384d24d309c16 [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
The Android Open Source Project96cb4a42009-01-15 16:12:12 -08001417 case R.id.select_text_id:
1418 getTopWindow().emulateShiftHeld();
1419 break;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001420 case R.id.page_info_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001421 showPageInfo(mTabControl.getCurrentTab(), false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001422 break;
1423
The Android Open Source Projected217d92008-12-17 18:05:52 -08001424 case R.id.classic_history_menu_id:
1425 loadHistory();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001426 break;
1427
1428 case R.id.bookmark_page_menu_id:
1429 Browser.saveBookmark(this, getTopWindow().getTitle(),
1430 getTopWindow().getUrl());
1431 break;
1432
1433 case R.id.share_page_menu_id:
1434 Browser.sendString(this, getTopWindow().getUrl());
1435 break;
1436
1437 case R.id.dump_nav_menu_id:
1438 getTopWindow().debugDump();
1439 break;
1440
1441 case R.id.zoom_menu_id:
1442 // FIXME: Can we move this out of WebView? How does this work
1443 // for a subwindow?
1444 getTopWindow().invokeZoomPicker();
1445 break;
1446
1447 case R.id.zoom_in_menu_id:
1448 getTopWindow().zoomIn();
1449 break;
1450
1451 case R.id.zoom_out_menu_id:
1452 getTopWindow().zoomOut();
1453 break;
1454
1455 case R.id.view_downloads_menu_id:
1456 viewDownloads(null);
1457 break;
1458
1459 case R.id.flip_orientation_menu_id:
1460 if (mSettings.getOrientation() !=
1461 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001462 mSettings.setOrientation(this,
1463 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001464 } else {
1465 mSettings.setOrientation(this,
1466 ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
1467 }
1468 setRequestedOrientation(mSettings.getOrientation());
1469 break;
1470
1471 // -- Tab menu
1472 case R.id.view_tab_menu_id:
1473 if (mTabListener != null && mTabOverview != null) {
1474 int pos = mTabOverview.getContextMenuPosition(item);
1475 mTabOverview.setCurrentIndex(pos);
1476 mTabListener.onClick(pos);
1477 }
1478 break;
1479
1480 case R.id.remove_tab_menu_id:
1481 if (mTabListener != null && mTabOverview != null) {
1482 int pos = mTabOverview.getContextMenuPosition(item);
1483 mTabListener.remove(pos);
1484 }
1485 break;
1486
1487 case R.id.new_tab_menu_id:
1488 // No need to check for mTabOverview here since we are not
1489 // dependent on it for a position.
1490 if (mTabListener != null) {
1491 // If the overview happens to be non-null, make the "New
1492 // Tab" cell visible.
1493 if (mTabOverview != null) {
1494 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1495 }
1496 mTabListener.onClick(ImageGrid.NEW_TAB);
1497 }
1498 break;
1499
1500 case R.id.bookmark_tab_menu_id:
1501 if (mTabListener != null && mTabOverview != null) {
1502 int pos = mTabOverview.getContextMenuPosition(item);
1503 TabControl.Tab t = mTabControl.getTab(pos);
1504 // Since we called populatePickerData for all of the
1505 // tabs, getTitle and getUrl will return appropriate
1506 // values.
1507 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1508 t.getUrl());
1509 }
1510 break;
1511
1512 case R.id.history_tab_menu_id: {
1513 Intent i = new Intent(this, BrowserHistoryPage.class);
1514 i.putExtra("maxTabsOpen",
1515 mTabControl.getTabCount() >=
1516 TabControl.MAX_TABS);
1517 startActivityForResult(i, CLASSIC_HISTORY_PAGE);
1518 }
1519 break;
1520
1521 case R.id.bookmarks_tab_menu_id:
1522 bookmarksPicker();
1523 break;
1524
1525 case R.id.properties_tab_menu_id:
1526 if (mTabListener != null && mTabOverview != null) {
1527 int pos = mTabOverview.getContextMenuPosition(item);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001528 showPageInfo(mTabControl.getTab(pos), false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001529 }
1530 break;
1531
The Android Open Source Projected217d92008-12-17 18:05:52 -08001532 case R.id.window_one_menu_id:
1533 case R.id.window_two_menu_id:
1534 case R.id.window_three_menu_id:
1535 case R.id.window_four_menu_id:
1536 case R.id.window_five_menu_id:
1537 case R.id.window_six_menu_id:
1538 case R.id.window_seven_menu_id:
1539 case R.id.window_eight_menu_id:
1540 {
1541 int menuid = item.getItemId();
1542 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1543 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1544 TabControl.Tab desiredTab = mTabControl.getTab(id);
1545 if (desiredTab != null &&
1546 desiredTab != mTabControl.getCurrentTab()) {
1547 switchTabs(mTabControl.getCurrentIndex(), id, false);
1548 }
1549 break;
1550 }
1551 }
1552 }
1553 break;
1554
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001555 default:
1556 if (!super.onOptionsItemSelected(item)) {
1557 return false;
1558 }
1559 // Otherwise fall through.
1560 }
1561 mCanChord = false;
1562 return true;
1563 }
1564
1565 public void closeFind() {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001566 mMenuState = R.id.MAIN_MENU;
1567 }
1568
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001569 @Override public boolean onPrepareOptionsMenu(Menu menu)
1570 {
1571 // This happens when the user begins to hold down the menu key, so
1572 // allow them to chord to get a shortcut.
1573 mCanChord = true;
1574 // Note: setVisible will decide whether an item is visible; while
1575 // setEnabled() will decide whether an item is enabled, which also means
1576 // whether the matching shortcut key will function.
1577 super.onPrepareOptionsMenu(menu);
1578 switch (mMenuState) {
1579 case R.id.TAB_MENU:
1580 if (mCurrentMenuState != mMenuState) {
1581 menu.setGroupVisible(R.id.MAIN_MENU, false);
1582 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1583 menu.setGroupVisible(R.id.TAB_MENU, true);
1584 menu.setGroupEnabled(R.id.TAB_MENU, true);
1585 }
1586 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1587 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1588 tab.setVisible(newT);
1589 tab.setEnabled(newT);
1590 break;
1591 case EMPTY_MENU:
1592 if (mCurrentMenuState != mMenuState) {
1593 menu.setGroupVisible(R.id.MAIN_MENU, false);
1594 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1595 menu.setGroupVisible(R.id.TAB_MENU, false);
1596 menu.setGroupEnabled(R.id.TAB_MENU, false);
1597 }
1598 break;
1599 default:
1600 if (mCurrentMenuState != mMenuState) {
1601 menu.setGroupVisible(R.id.MAIN_MENU, true);
1602 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1603 menu.setGroupVisible(R.id.TAB_MENU, false);
1604 menu.setGroupEnabled(R.id.TAB_MENU, false);
1605 }
1606 final WebView w = getTopWindow();
1607 boolean canGoBack = w.canGoBack();
1608 final MenuItem back = menu.findItem(R.id.back_menu_id);
1609 back.setVisible(canGoBack);
1610 back.setEnabled(canGoBack);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001611 final MenuItem flip =
1612 menu.findItem(R.id.flip_orientation_menu_id);
1613 boolean keyboardClosed =
The Android Open Source Projected217d92008-12-17 18:05:52 -08001614 getResources().getConfiguration().hardKeyboardHidden ==
1615 Configuration.HARDKEYBOARDHIDDEN_YES;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001616 flip.setEnabled(keyboardClosed);
1617
1618 boolean isHome = mSettings.getHomePage().equals(w.getUrl());
1619 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1620 home.setVisible(!isHome);
1621 home.setEnabled(!isHome);
1622
1623 menu.findItem(R.id.forward_menu_id)
1624 .setEnabled(w.canGoForward());
1625
1626 menu.findItem(R.id.zoom_in_menu_id).setVisible(false);
1627 menu.findItem(R.id.zoom_out_menu_id).setVisible(false);
1628
1629 // decide whether to show the share link option
1630 PackageManager pm = getPackageManager();
1631 Intent send = new Intent(Intent.ACTION_SEND);
1632 send.setType("text/plain");
1633 List<ResolveInfo> list = pm.queryIntentActivities(send,
1634 PackageManager.MATCH_DEFAULT_ONLY);
1635 menu.findItem(R.id.share_page_menu_id).setVisible(
1636 list.size() > 0);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001637
1638 // Hide the menu+<window number> items
1639 // Can't set visibility in menu xml file b/c when a
1640 // group is set visible, all items are set visible.
1641 for (int i = 0; i < WINDOW_SHORTCUT_ID_ARRAY.length; i++) {
1642 menu.findItem(WINDOW_SHORTCUT_ID_ARRAY[i]).setVisible(false);
1643 }
1644
1645 // If there is only 1 window, the text will be "New window"
1646 final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1647 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1648 getString(R.string.view_tabs_condensed) :
1649 getString(R.string.tab_picker_new_tab));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001650
1651 boolean isNavDump = mSettings.isNavDump();
1652 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1653 nav.setVisible(isNavDump);
1654 nav.setEnabled(isNavDump);
1655 break;
1656 }
1657 mCurrentMenuState = mMenuState;
1658 return true;
1659 }
1660
1661 @Override
1662 public void onCreateContextMenu(ContextMenu menu, View v,
1663 ContextMenuInfo menuInfo) {
1664 WebView webview = (WebView) v;
1665 WebView.HitTestResult result = webview.getHitTestResult();
1666 if (result == null) {
1667 return;
1668 }
1669
1670 int type = result.getType();
1671 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1672 Log.w(LOGTAG,
1673 "We should not show context menu when nothing is touched");
1674 return;
1675 }
1676 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1677 // let TextView handles context menu
1678 return;
1679 }
1680
1681 // Note, http://b/issue?id=1106666 is requesting that
1682 // an inflated menu can be used again. This is not available
1683 // yet, so inflate each time (yuk!)
1684 MenuInflater inflater = getMenuInflater();
1685 inflater.inflate(R.menu.browsercontext, menu);
1686
1687 // Show the correct menu group
1688 String extra = result.getExtra();
1689 menu.setGroupVisible(R.id.PHONE_MENU,
1690 type == WebView.HitTestResult.PHONE_TYPE);
1691 menu.setGroupVisible(R.id.EMAIL_MENU,
1692 type == WebView.HitTestResult.EMAIL_TYPE);
1693 menu.setGroupVisible(R.id.GEO_MENU,
1694 type == WebView.HitTestResult.GEO_TYPE);
1695 menu.setGroupVisible(R.id.IMAGE_MENU,
The Android Open Source Projected217d92008-12-17 18:05:52 -08001696 type == WebView.HitTestResult.IMAGE_TYPE
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001697 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1698 menu.setGroupVisible(R.id.ANCHOR_MENU,
The Android Open Source Projected217d92008-12-17 18:05:52 -08001699 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001700 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1701
1702 // Setup custom handling depending on the type
1703 switch (type) {
1704 case WebView.HitTestResult.PHONE_TYPE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001705 menu.setHeaderTitle(Uri.decode(extra));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001706 menu.findItem(R.id.dial_context_menu_id).setIntent(
1707 new Intent(Intent.ACTION_VIEW, Uri
1708 .parse(WebView.SCHEME_TEL + extra)));
The Android Open Source Projected217d92008-12-17 18:05:52 -08001709 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1710 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1711 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001712 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1713 addIntent);
1714 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1715 new Copy(extra));
1716 break;
1717
1718 case WebView.HitTestResult.EMAIL_TYPE:
1719 menu.setHeaderTitle(extra);
1720 menu.findItem(R.id.email_context_menu_id).setIntent(
1721 new Intent(Intent.ACTION_VIEW, Uri
1722 .parse(WebView.SCHEME_MAILTO + extra)));
1723 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1724 new Copy(extra));
1725 break;
1726
1727 case WebView.HitTestResult.GEO_TYPE:
1728 menu.setHeaderTitle(extra);
1729 menu.findItem(R.id.map_context_menu_id).setIntent(
1730 new Intent(Intent.ACTION_VIEW, Uri
1731 .parse(WebView.SCHEME_GEO
1732 + URLEncoder.encode(extra))));
1733 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1734 new Copy(extra));
1735 break;
1736
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001737 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1738 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001739 TextView titleView = (TextView) LayoutInflater.from(this)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001740 .inflate(android.R.layout.browser_link_context_header,
1741 null);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001742 titleView.setText(extra);
1743 menu.setHeaderView(titleView);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001744 // decide whether to show the open link in new tab option
1745 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1746 mTabControl.getTabCount() < TabControl.MAX_TABS);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001747 PackageManager pm = getPackageManager();
1748 Intent send = new Intent(Intent.ACTION_SEND);
1749 send.setType("text/plain");
1750 List<ResolveInfo> list = pm.queryIntentActivities(send,
1751 PackageManager.MATCH_DEFAULT_ONLY);
1752 menu.findItem(R.id.share_link_context_menu_id).setVisible(
1753 list.size() > 0);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001754 break;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001755
1756 case WebView.HitTestResult.IMAGE_TYPE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001757 menu.setHeaderTitle(extra);
1758 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1759 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1760 menu.findItem(R.id.download_context_menu_id).
1761 setOnMenuItemClickListener(new Download(extra));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001762 break;
1763
1764 default:
1765 Log.w(LOGTAG, "We should not get here.");
1766 break;
1767 }
1768 }
1769
1770 // Used by attachTabToContentView for the WebView's ZoomControl widget.
1771 private static final FrameLayout.LayoutParams ZOOM_PARAMS =
1772 new FrameLayout.LayoutParams(
1773 ViewGroup.LayoutParams.FILL_PARENT,
1774 ViewGroup.LayoutParams.WRAP_CONTENT,
1775 Gravity.BOTTOM);
1776
1777 // Attach the given tab to the content view.
1778 private void attachTabToContentView(TabControl.Tab t) {
1779 final WebView main = t.getWebView();
1780 // Attach the main WebView.
1781 mContentView.addView(main, COVER_SCREEN_PARAMS);
1782 // Attach the Zoom control widget and hide it.
1783 final View zoom = main.getZoomControls();
1784 mContentView.addView(zoom, ZOOM_PARAMS);
1785 zoom.setVisibility(View.GONE);
1786 // Attach the sub window if necessary
1787 attachSubWindow(t);
1788 // Request focus on the top window.
1789 t.getTopWindow().requestFocus();
1790 }
1791
1792 // Attach a sub window to the main WebView of the given tab.
1793 private void attachSubWindow(TabControl.Tab t) {
1794 // If a sub window exists, attach it to the content view.
1795 final WebView subView = t.getSubWebView();
1796 if (subView != null) {
1797 final View container = t.getSubWebViewContainer();
1798 mContentView.addView(container, COVER_SCREEN_PARAMS);
1799 subView.requestFocus();
1800 }
1801 }
1802
1803 // Remove the given tab from the content view.
1804 private void removeTabFromContentView(TabControl.Tab t) {
1805 // Remove the Zoom widget and the main WebView.
1806 mContentView.removeView(t.getWebView().getZoomControls());
1807 mContentView.removeView(t.getWebView());
1808 // Remove the sub window if it exists.
1809 if (t.getSubWebView() != null) {
1810 mContentView.removeView(t.getSubWebViewContainer());
1811 }
1812 }
1813
1814 // Remove the sub window if it exists. Also called by TabControl when the
1815 // user clicks the 'X' to dismiss a sub window.
1816 /* package */ void dismissSubWindow(TabControl.Tab t) {
1817 final WebView mainView = t.getWebView();
1818 if (t.getSubWebView() != null) {
1819 // Remove the container view and request focus on the main WebView.
1820 mContentView.removeView(t.getSubWebViewContainer());
1821 mainView.requestFocus();
1822 // Tell the TabControl to dismiss the subwindow. This will destroy
1823 // the WebView.
1824 mTabControl.dismissSubWindow(t);
1825 }
1826 }
1827
1828 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
1829 private void sendAnimateFromOverview(final TabControl.Tab tab,
1830 final boolean newTab, final String url, final int delay,
1831 final Message msg) {
1832 // Set the current tab.
1833 mTabControl.setCurrentTab(tab);
1834 // Attach the WebView so it will layout.
1835 attachTabToContentView(tab);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001836 // Set the view to invisibile for now.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001837 tab.getWebView().setVisibility(View.INVISIBLE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001838 // If there is a sub window, make it invisible too.
1839 if (tab.getSubWebView() != null) {
1840 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
1841 }
1842 // Create our fake animating view.
1843 final AnimatingView view = new AnimatingView(this, tab);
1844 // Attach it to the view system and make in invisible so it will
1845 // layout but not flash white on the screen.
1846 mContentView.addView(view, COVER_SCREEN_PARAMS);
1847 view.setVisibility(View.INVISIBLE);
1848 // Send the animate message.
1849 final HashMap map = new HashMap();
1850 map.put("view", view);
1851 map.put("url", url);
1852 map.put("msg", msg);
1853 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1854 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
1855 // Increment the count to indicate that we are in an animation.
1856 mAnimationCount++;
1857 // Remove the listener so we don't get any more tab changes.
The Android Open Source Projected217d92008-12-17 18:05:52 -08001858 mTabOverview.setListener(null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001859 mTabListener = null;
The Android Open Source Projected217d92008-12-17 18:05:52 -08001860 // Make the menu empty until the animation completes.
1861 mMenuState = EMPTY_MENU;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001862
1863 }
1864
1865 // 500ms animation with 800ms delay
1866 private static final int TAB_ANIMATION_DURATION = 500;
1867 private static final int TAB_OVERVIEW_DELAY = 800;
1868
1869 // Called by TabControl when a tab is requesting focus
1870 /* package */ void showTab(TabControl.Tab t) {
1871 // Disallow focus change during a tab animation.
1872 if (mAnimationCount > 0) {
1873 return;
1874 }
1875 int delay = 0;
1876 if (mTabOverview == null) {
1877 // Add a delay so the tab overview can be shown before the second
1878 // animation begins.
1879 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1880 tabPicker(false, mTabControl.getTabIndex(t), false);
1881 }
1882 sendAnimateFromOverview(t, false, null, delay, null);
1883 }
1884
1885 // This method does a ton of stuff. It will attempt to create a new tab
1886 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1887 // url isn't null, it will load the given url. If the tab overview is not
1888 // showing, it will animate to the tab overview, create a new tab and
1889 // animate away from it. After the animation completes, it will dispatch
1890 // the given Message. If the tab overview is already showing (i.e. this
1891 // method is called from TabListener.onClick(), the method will animate
1892 // away from the tab overview.
The Android Open Source Projected217d92008-12-17 18:05:52 -08001893 private void openTabAndShow(String url, final Message msg,
1894 boolean closeOnExit) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001895 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1896 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1897 if (newTab) {
1898 int delay = 0;
1899 // If the tab overview is up and there are animations, just load
1900 // the url.
1901 if (mTabOverview != null && mAnimationCount > 0) {
1902 if (url != null) {
1903 // We should not have a msg here since onCreateWindow
1904 // checks the animation count and every other caller passes
1905 // null.
1906 assert msg == null;
1907 // just dismiss the subwindow and load the given url.
1908 dismissSubWindow(currentTab);
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001909 currentTab.getWebView().loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001910 }
1911 } else {
1912 // show mTabOverview if it is not there.
1913 if (mTabOverview == null) {
1914 // We have to delay the animation from the tab picker by the
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001915 // length of the tab animation. Add a delay so the tab
1916 // overview can be shown before the second animation begins.
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001917 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1918 tabPicker(false, ImageGrid.NEW_TAB, false);
1919 }
1920 // Animate from the Tab overview after any animations have
1921 // finished.
The Android Open Source Projected217d92008-12-17 18:05:52 -08001922 sendAnimateFromOverview(mTabControl.createNewTab(closeOnExit),
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001923 true, url, delay, msg);
1924 }
1925 } else if (url != null) {
1926 // We should not have a msg here.
1927 assert msg == null;
1928 if (mTabOverview != null && mAnimationCount == 0) {
1929 sendAnimateFromOverview(currentTab, false, url,
1930 TAB_OVERVIEW_DELAY, null);
1931 } else {
1932 // Get rid of the subwindow if it exists
1933 dismissSubWindow(currentTab);
1934 // Load the given url.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001935 currentTab.getWebView().loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001936 }
1937 }
1938 }
1939
1940 private Animation createTabAnimation(final AnimatingView view,
1941 final View cell, boolean scaleDown) {
1942 final AnimationSet set = new AnimationSet(true);
1943 final float scaleX = (float) cell.getWidth() / view.getWidth();
1944 final float scaleY = (float) cell.getHeight() / view.getHeight();
1945 if (scaleDown) {
1946 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
1947 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
1948 cell.getTop()));
1949 } else {
1950 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
1951 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
1952 cell.getTop(), 0));
1953 }
1954 set.setDuration(TAB_ANIMATION_DURATION);
1955 set.setInterpolator(new DecelerateInterpolator());
1956 return set;
1957 }
1958
1959 // Animate to the tab overview. currentIndex tells us which position to
1960 // animate to and newIndex is the position that should be selected after
1961 // the animation completes.
1962 // If remove is true, after the animation stops, a confirmation dialog will
1963 // be displayed to the user.
1964 private void animateToTabOverview(final int newIndex, final boolean remove,
1965 final AnimatingView view) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001966 // Find the view in the ImageGrid allowing for the "New Tab" cell.
1967 int position = mTabControl.getTabIndex(view.mTab);
1968 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
1969 position++;
1970 }
1971
1972 // Offset the tab position with the first visible position to get a
1973 // number between 0 and 3.
1974 position -= mTabOverview.getFirstVisiblePosition();
1975
1976 // Grab the view that we are going to animate to.
1977 final View v = mTabOverview.getChildAt(position);
1978
1979 final Animation.AnimationListener l =
1980 new Animation.AnimationListener() {
1981 public void onAnimationStart(Animation a) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08001982 mTabOverview.requestFocus();
1983 // Clear the listener so we don't trigger a tab
1984 // selection.
1985 mTabOverview.setListener(null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001986 }
1987 public void onAnimationRepeat(Animation a) {}
1988 public void onAnimationEnd(Animation a) {
1989 // We are no longer animating so decrement the count.
1990 mAnimationCount--;
1991 // Make the view GONE so that it will not draw between
1992 // now and when the Runnable is handled.
1993 view.setVisibility(View.GONE);
1994 // Post a runnable since we can't modify the view
1995 // hierarchy during this callback.
1996 mHandler.post(new Runnable() {
1997 public void run() {
1998 // Remove the AnimatingView.
1999 mContentView.removeView(view);
The Android Open Source Projected217d92008-12-17 18:05:52 -08002000 // Make newIndex visible.
2001 mTabOverview.setCurrentIndex(newIndex);
2002 // Restore the listener.
2003 mTabOverview.setListener(mTabListener);
2004 // Change the menu to TAB_MENU if the
2005 // ImageGrid is interactive.
2006 if (mTabOverview.isLive()) {
2007 mMenuState = R.id.TAB_MENU;
2008 mTabOverview.requestFocus();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002009 }
2010 // If a remove was requested, remove the tab.
2011 if (remove) {
2012 // During a remove, the current tab has
2013 // already changed. Remember the current one
2014 // here.
2015 final TabControl.Tab currentTab =
2016 mTabControl.getCurrentTab();
2017 // Remove the tab at newIndex from
2018 // TabControl and the tab overview.
2019 final TabControl.Tab tab =
2020 mTabControl.getTab(newIndex);
2021 mTabControl.removeTab(tab);
2022 // Restore the current tab.
2023 if (currentTab != tab) {
2024 mTabControl.setCurrentTab(currentTab);
2025 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002026 mTabOverview.remove(newIndex);
2027 // Make the current tab visible.
2028 mTabOverview.setCurrentIndex(
2029 mTabControl.getCurrentIndex());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002030 }
2031 }
2032 });
2033 }
2034 };
2035
2036 // Do an animation if there is a view to animate to.
2037 if (v != null) {
2038 // Create our animation
2039 final Animation anim = createTabAnimation(view, v, true);
2040 anim.setAnimationListener(l);
2041 // Start animating
2042 view.startAnimation(anim);
2043 } else {
2044 // If something goes wrong and we didn't find a view to animate to,
2045 // just do everything here.
2046 l.onAnimationStart(null);
2047 l.onAnimationEnd(null);
2048 }
2049 }
2050
2051 // Animate from the tab picker. The index supplied is the index to animate
2052 // from.
2053 private void animateFromTabOverview(final AnimatingView view,
2054 final boolean newTab, final String url, final Message msg) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002055 // firstVisible is the first visible tab on the screen. This helps
2056 // to know which corner of the screen the selected tab is.
2057 int firstVisible = mTabOverview.getFirstVisiblePosition();
2058 // tabPosition is the 0-based index of of the tab being opened
2059 int tabPosition = mTabControl.getTabIndex(view.mTab);
2060 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2061 // Add one to make room for the "New Tab" cell.
2062 tabPosition++;
2063 }
2064 // If this is a new tab, animate from the "New Tab" cell.
2065 if (newTab) {
2066 tabPosition = 0;
2067 }
2068 // Location corresponds to the four corners of the screen.
2069 // A new tab or 0 is upper left, 0 for an old tab is upper
2070 // right, 1 is lower left, and 2 is lower right
2071 int location = tabPosition - firstVisible;
2072
2073 // Find the view at this location.
2074 final View v = mTabOverview.getChildAt(location);
2075
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002076 // Wait until the animation completes to load the url.
2077 final Animation.AnimationListener l =
2078 new Animation.AnimationListener() {
2079 public void onAnimationStart(Animation a) {}
2080 public void onAnimationRepeat(Animation a) {}
2081 public void onAnimationEnd(Animation a) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002082 mHandler.post(new Runnable() {
2083 public void run() {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002084 mContentView.removeView(view);
2085 // Dismiss the tab overview. If the cell at the
2086 // given location is null, set the fade
2087 // parameter to true.
2088 dismissTabOverview(v == null);
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002089 TabControl.Tab t =
2090 mTabControl.getCurrentTab();
2091 WebView w = t.getWebView();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002092 if (url != null) {
2093 // Dismiss the subwindow if one exists.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002094 dismissSubWindow(t);
2095 w.loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002096 }
2097 mMenuState = R.id.MAIN_MENU;
2098 // Resume regular updates.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002099 w.resumeTimers();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002100 // Dispatch the message after the animation
2101 // completes.
2102 if (msg != null) {
2103 msg.sendToTarget();
2104 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002105 // The animation is done and the tab overview is
2106 // gone so allow key events and other animations
2107 // to begin.
2108 mAnimationCount--;
2109 // Reset all the title bar info.
2110 resetTitle();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002111 }
2112 });
2113 }
2114 };
2115
2116 if (v != null) {
2117 final Animation anim = createTabAnimation(view, v, false);
2118 // Set the listener and start animating
2119 anim.setAnimationListener(l);
2120 view.startAnimation(anim);
2121 // Make the view VISIBLE during the animation.
2122 view.setVisibility(View.VISIBLE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002123 } else {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002124 // Go ahead and load the url.
2125 l.onAnimationEnd(null);
2126 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002127 }
2128
2129 // Dismiss the tab overview applying a fade if needed.
2130 private void dismissTabOverview(final boolean fade) {
2131 if (fade) {
2132 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2133 anim.setDuration(500);
2134 anim.startNow();
2135 mTabOverview.startAnimation(anim);
2136 }
2137 // Just in case there was a problem with animating away from the tab
2138 // overview
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002139 mTabControl.getCurrentWebView().setVisibility(View.VISIBLE);
The Android Open Source Projected217d92008-12-17 18:05:52 -08002140 // Make the sub window container visible.
2141 if (mTabControl.getCurrentSubWindow() != null) {
2142 mTabControl.getCurrentTab().getSubWebViewContainer()
2143 .setVisibility(View.VISIBLE);
2144 }
2145 mContentView.removeView(mTabOverview);
2146 mTabOverview.clear();
2147 mTabOverview = null;
2148 mTabListener = null;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002149 }
2150
2151 private void openTab(String url) {
2152 if (mSettings.openInBackground()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002153 TabControl.Tab t = mTabControl.createNewTab(false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002154 if (t != null) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002155 t.getWebView().loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002156 }
2157 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002158 openTabAndShow(url, null, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002159 }
2160 }
2161
2162 private class Copy implements OnMenuItemClickListener {
2163 private CharSequence mText;
2164
2165 public boolean onMenuItemClick(MenuItem item) {
2166 copy(mText);
2167 return true;
2168 }
2169
2170 public Copy(CharSequence toCopy) {
2171 mText = toCopy;
2172 }
2173 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002174
2175 private class Download implements OnMenuItemClickListener {
2176 private String mText;
2177
2178 public boolean onMenuItemClick(MenuItem item) {
2179 onDownloadStartNoStream(mText, null, null, null, -1);
2180 return true;
2181 }
2182
2183 public Download(String toDownload) {
2184 mText = toDownload;
2185 }
2186 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002187
2188 private void copy(CharSequence text) {
2189 try {
2190 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2191 if (clip != null) {
2192 clip.setClipboardText(text);
2193 }
2194 } catch (android.os.RemoteException e) {
2195 Log.e(LOGTAG, "Copy failed", e);
2196 }
2197 }
2198
2199 /**
2200 * Resets the browser title-view to whatever it must be (for example, if we
2201 * load a page from history).
2202 */
2203 private void resetTitle() {
2204 resetLockIcon();
2205 resetTitleIconAndProgress();
2206 }
2207
2208 /**
2209 * Resets the browser title-view to whatever it must be
2210 * (for example, if we had a loading error)
2211 * When we have a new page, we call resetTitle, when we
2212 * have to reset the titlebar to whatever it used to be
2213 * (for example, if the user chose to stop loading), we
2214 * call resetTitleAndRevertLockIcon.
2215 */
2216 /* package */ void resetTitleAndRevertLockIcon() {
2217 revertLockIcon();
2218 resetTitleIconAndProgress();
2219 }
2220
2221 /**
2222 * Reset the title, favicon, and progress.
2223 */
2224 private void resetTitleIconAndProgress() {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002225 WebView current = mTabControl.getCurrentWebView();
2226 if (current == null) {
2227 return;
2228 }
2229 resetTitleAndIcon(current);
2230 int progress = current.getProgress();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002231 mInLoad = (progress != 100);
2232 updateInLoadMenuItems();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002233 mWebChromeClient.onProgressChanged(current, progress);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002234 }
2235
2236 // Reset the title and the icon based on the given item.
2237 private void resetTitleAndIcon(WebView view) {
2238 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2239 if (item != null) {
2240 setUrlTitle(item.getUrl(), item.getTitle());
2241 setFavicon(item.getFavicon());
2242 } else {
2243 setUrlTitle(null, null);
2244 setFavicon(null);
2245 }
2246 }
2247
2248 /**
2249 * Sets a title composed of the URL and the title string.
2250 * @param url The URL of the site being loaded.
2251 * @param title The title of the site being loaded.
2252 */
2253 private void setUrlTitle(String url, String title) {
2254 mUrl = url;
2255 mTitle = title;
2256
The Android Open Source Projected217d92008-12-17 18:05:52 -08002257 // While the tab overview is animating or being shown, block changes
2258 // to the title.
2259 if (mAnimationCount == 0 && mTabOverview == null) {
2260 setTitle(buildUrlTitle(url, title));
2261 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002262 }
2263
2264 /**
2265 * Builds and returns the page title, which is some
2266 * combination of the page URL and title.
2267 * @param url The URL of the site being loaded.
2268 * @param title The title of the site being loaded.
2269 * @return The page title.
2270 */
2271 private String buildUrlTitle(String url, String title) {
2272 String urlTitle = "";
2273
2274 if (url != null) {
2275 String titleUrl = buildTitleUrl(url);
2276
2277 if (title != null && 0 < title.length()) {
2278 if (titleUrl != null && 0 < titleUrl.length()) {
2279 urlTitle = titleUrl + ": " + title;
2280 } else {
2281 urlTitle = title;
2282 }
2283 } else {
2284 if (titleUrl != null) {
2285 urlTitle = titleUrl;
2286 }
2287 }
2288 }
2289
2290 return urlTitle;
2291 }
2292
2293 /**
2294 * @param url The URL to build a title version of the URL from.
2295 * @return The title version of the URL or null if fails.
2296 * The title version of the URL can be either the URL hostname,
2297 * or the hostname with an "https://" prefix (for secure URLs),
2298 * or an empty string if, for example, the URL in question is a
2299 * file:// URL with no hostname.
2300 */
2301 private static String buildTitleUrl(String url) {
2302 String titleUrl = null;
2303
2304 if (url != null) {
2305 try {
2306 // parse the url string
2307 URL urlObj = new URL(url);
2308 if (urlObj != null) {
2309 titleUrl = "";
2310
2311 String protocol = urlObj.getProtocol();
2312 String host = urlObj.getHost();
2313
2314 if (host != null && 0 < host.length()) {
2315 titleUrl = host;
2316 if (protocol != null) {
2317 // if a secure site, add an "https://" prefix!
2318 if (protocol.equalsIgnoreCase("https")) {
2319 titleUrl = protocol + "://" + host;
2320 }
2321 }
2322 }
2323 }
2324 } catch (MalformedURLException e) {}
2325 }
2326
2327 return titleUrl;
2328 }
2329
2330 // Set the favicon in the title bar.
2331 private void setFavicon(Bitmap icon) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002332 // While the tab overview is animating or being shown, block changes to
2333 // the favicon.
2334 if (mAnimationCount > 0 || mTabOverview != null) {
2335 return;
2336 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002337 Drawable[] array = new Drawable[2];
2338 PaintDrawable p = new PaintDrawable(Color.WHITE);
2339 p.setCornerRadius(3f);
2340 array[0] = p;
2341 if (icon == null) {
2342 array[1] = mGenericFavicon;
2343 } else {
2344 array[1] = new BitmapDrawable(icon);
2345 }
2346 LayerDrawable d = new LayerDrawable(array);
2347 d.setLayerInset(1, 2, 2, 2, 2);
2348 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
2349 }
2350
2351 /**
2352 * Saves the current lock-icon state before resetting
2353 * the lock icon. If we have an error, we may need to
2354 * roll back to the previous state.
2355 */
2356 private void saveLockIcon() {
2357 mPrevLockType = mLockIconType;
2358 }
2359
2360 /**
2361 * Reverts the lock-icon state to the last saved state,
2362 * for example, if we had an error, and need to cancel
2363 * the load.
2364 */
2365 private void revertLockIcon() {
2366 mLockIconType = mPrevLockType;
2367
2368 if (Config.LOGV) {
2369 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2370 " revert lock icon to " + mLockIconType);
2371 }
2372
2373 updateLockIconImage(mLockIconType);
2374 }
2375
The Android Open Source Projected217d92008-12-17 18:05:52 -08002376 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002377 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2378 // Animate to the tab picker, remove the current tab, then
2379 // animate away from the tab picker to the parent WebView.
The Android Open Source Projected217d92008-12-17 18:05:52 -08002380 tabPicker(false, indexFrom, remove);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002381 // Change to the parent tab
2382 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2383 if (tab != null) {
2384 sendAnimateFromOverview(tab, false, null, delay, null);
2385 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002386 // Increment this here so that no other animations can happen in
2387 // between the end of the tab picker transition and the beginning
2388 // of openTabAndShow. This has a matching decrement in the handler
2389 // of OPEN_TAB_AND_SHOW.
2390 mAnimationCount++;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002391 // Send a message to open a new tab.
2392 mHandler.sendMessageDelayed(
2393 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2394 mSettings.getHomePage()), delay);
2395 }
2396 }
2397
2398 private void goBackOnePageOrQuit() {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002399 TabControl.Tab current = mTabControl.getCurrentTab();
2400 if (current == null) {
2401 /*
2402 * Instead of finishing the activity, simply push this to the back
2403 * of the stack and let ActivityManager to choose the foreground
2404 * activity. As BrowserActivity is singleTask, it will be always the
2405 * root of the task. So we can use either true or false for
2406 * moveTaskToBack().
2407 */
2408 moveTaskToBack(true);
2409 }
2410 WebView w = current.getWebView();
2411 if (w.canGoBack()) {
2412 w.goBack();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002413 } else {
2414 // Check to see if we are closing a window that was created by
2415 // another window. If so, we switch back to that window.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002416 TabControl.Tab parent = current.getParentTab();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002417 if (parent != null) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002418 switchTabs(mTabControl.getCurrentIndex(),
2419 mTabControl.getTabIndex(parent), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002420 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002421 if (current.closeOnExit()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002422 if (mTabControl.getTabCount() == 1) {
2423 finish();
2424 return;
2425 }
2426 // call pauseWebView() now, we won't be able to call it in
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002427 // onPause() as the WebView won't be valid.
The Android Open Source Projected217d92008-12-17 18:05:52 -08002428 pauseWebView();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002429 removeTabFromContentView(current);
2430 mTabControl.removeTab(current);
The Android Open Source Projected217d92008-12-17 18:05:52 -08002431 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002432 /*
2433 * Instead of finishing the activity, simply push this to the back
2434 * of the stack and let ActivityManager to choose the foreground
2435 * activity. As BrowserActivity is singleTask, it will be always the
2436 * root of the task. So we can use either true or false for
2437 * moveTaskToBack().
2438 */
2439 moveTaskToBack(true);
2440 }
2441 }
2442 }
2443
2444 public KeyTracker.State onKeyTracker(int keyCode,
2445 KeyEvent event,
2446 KeyTracker.Stage stage,
2447 int duration) {
2448 // if onKeyTracker() is called after activity onStop()
2449 // because of accumulated key events,
2450 // we should ignore it as browser is not active any more.
2451 WebView topWindow = getTopWindow();
2452 if (topWindow == null)
2453 return KeyTracker.State.NOT_TRACKING;
2454
2455 if (keyCode == KeyEvent.KEYCODE_BACK) {
2456 // During animations, block the back key so that other animations
2457 // are not triggered and so that we don't end up destroying all the
2458 // WebViews before finishing the animation.
2459 if (mAnimationCount > 0) {
2460 return KeyTracker.State.DONE_TRACKING;
2461 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002462 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2463 loadHistory();
2464 return KeyTracker.State.DONE_TRACKING;
2465 } else if (stage == KeyTracker.Stage.UP) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002466 // FIXME: Currently, we do not have a notion of the
2467 // history picker for the subwindow, but maybe we
2468 // should?
2469 WebView subwindow = mTabControl.getCurrentSubWindow();
2470 if (subwindow != null) {
2471 if (subwindow.canGoBack()) {
2472 subwindow.goBack();
2473 } else {
2474 dismissSubWindow(mTabControl.getCurrentTab());
2475 }
2476 } else {
2477 goBackOnePageOrQuit();
2478 }
2479 return KeyTracker.State.DONE_TRACKING;
2480 }
2481 return KeyTracker.State.KEEP_TRACKING;
2482 }
2483 return KeyTracker.State.NOT_TRACKING;
2484 }
2485
2486 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2487 if (keyCode == KeyEvent.KEYCODE_MENU) {
2488 mMenuIsDown = true;
2489 }
2490 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2491 if (!handled) {
2492 switch (keyCode) {
2493 case KeyEvent.KEYCODE_SPACE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002494 if (event.isShiftPressed()) {
2495 getTopWindow().pageUp(false);
2496 } else {
2497 getTopWindow().pageDown(false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002498 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002499 handled = true;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002500 break;
2501
2502 default:
2503 break;
2504 }
2505 }
2506 return handled || super.onKeyDown(keyCode, event);
2507 }
2508
2509 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2510 if (keyCode == KeyEvent.KEYCODE_MENU) {
2511 mMenuIsDown = false;
2512 }
2513 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2514 }
2515
2516 private void stopLoading() {
2517 resetTitleAndRevertLockIcon();
2518 WebView w = getTopWindow();
2519 w.stopLoading();
2520 mWebViewClient.onPageFinished(w, w.getUrl());
2521
2522 cancelStopToast();
2523 mStopToast = Toast
2524 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2525 mStopToast.show();
2526 }
2527
2528 private void cancelStopToast() {
2529 if (mStopToast != null) {
2530 mStopToast.cancel();
2531 mStopToast = null;
2532 }
2533 }
2534
The Android Open Source Projected217d92008-12-17 18:05:52 -08002535 private void loadHistory() {
2536 Intent intent = new Intent(this, BrowserHistoryPage.class);
2537 intent.putExtra("maxTabsOpen",
2538 mTabControl.getTabCount() >= TabControl.MAX_TABS);
2539 startActivityForResult(intent, CLASSIC_HISTORY_PAGE);
2540 }
2541
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002542 // called by a non-UI thread to post the message
2543 public void postMessage(int what, int arg1, int arg2, Object obj) {
2544 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2545 }
2546
2547 // public message ids
2548 public final static int LOAD_URL = 1001;
2549 public final static int STOP_LOAD = 1002;
2550
2551 // Message Ids
2552 private static final int JS_CONFIRM = 101;
2553 private static final int FOCUS_NODE_HREF = 102;
The Android Open Source Projected217d92008-12-17 18:05:52 -08002554 private static final int CANCEL_CREDS_REQUEST = 103;
2555 private static final int ANIMATE_FROM_OVERVIEW = 104;
2556 private static final int ANIMATE_TO_OVERVIEW = 105;
2557 private static final int OPEN_TAB_AND_SHOW = 106;
2558 private static final int CHECK_MEMORY = 107;
2559 private static final int RELEASE_WAKELOCK = 108;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002560
2561 // Private handler for handling javascript and saving passwords
2562 private Handler mHandler = new Handler() {
2563
2564 public void handleMessage(Message msg) {
2565 switch (msg.what) {
2566 case JS_CONFIRM:
2567 JsResult res = (JsResult) msg.obj;
2568 if (msg.arg1 == 0) {
2569 res.cancel();
2570 } else {
2571 res.confirm();
2572 }
2573 break;
2574
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002575 case ANIMATE_FROM_OVERVIEW:
2576 final HashMap map = (HashMap) msg.obj;
2577 animateFromTabOverview((AnimatingView) map.get("view"),
2578 msg.arg1 == 1, (String) map.get("url"),
2579 (Message) map.get("msg"));
2580 break;
2581
2582 case ANIMATE_TO_OVERVIEW:
2583 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2584 (AnimatingView) msg.obj);
2585 break;
2586
2587 case OPEN_TAB_AND_SHOW:
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002588 // Decrement mAnimationCount before openTabAndShow because
2589 // the method relies on the value being 0 to start the next
2590 // animation.
2591 mAnimationCount--;
The Android Open Source Projected217d92008-12-17 18:05:52 -08002592 openTabAndShow((String) msg.obj, null, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002593 break;
2594
2595 case FOCUS_NODE_HREF:
2596 String url = (String) msg.getData().get("url");
2597 if (url == null || url.length() == 0) {
2598 break;
2599 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002600 HashMap focusNodeMap = (HashMap) msg.obj;
2601 WebView view = (WebView) focusNodeMap.get("webview");
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002602 // Only apply the action if the top window did not change.
2603 if (getTopWindow() != view) {
2604 break;
2605 }
2606 switch (msg.arg1) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002607 case R.id.open_context_menu_id:
2608 case R.id.view_image_context_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002609 loadURL(getTopWindow(), url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002610 break;
2611 case R.id.open_newtab_context_menu_id:
2612 openTab(url);
2613 break;
2614 case R.id.bookmark_context_menu_id:
2615 Intent intent = new Intent(BrowserActivity.this,
2616 AddBookmarkPage.class);
2617 intent.putExtra("url", url);
2618 startActivity(intent);
2619 break;
2620 case R.id.share_link_context_menu_id:
2621 Browser.sendString(BrowserActivity.this, url);
2622 break;
2623 case R.id.copy_link_context_menu_id:
2624 copy(url);
2625 break;
2626 case R.id.save_link_context_menu_id:
2627 case R.id.download_context_menu_id:
2628 onDownloadStartNoStream(url, null, null, null, -1);
2629 break;
2630 }
2631 break;
2632
2633 case LOAD_URL:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002634 loadURL(getTopWindow(), (String) msg.obj);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002635 break;
2636
2637 case STOP_LOAD:
2638 stopLoading();
2639 break;
2640
2641 case CANCEL_CREDS_REQUEST:
2642 resumeAfterCredentials();
2643 break;
2644
2645 case CHECK_MEMORY:
2646 // reschedule to check memory condition
2647 mHandler.removeMessages(CHECK_MEMORY);
2648 mHandler.sendMessageDelayed(mHandler.obtainMessage
2649 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2650 checkMemory();
2651 break;
2652
2653 case RELEASE_WAKELOCK:
2654 if (mWakeLock.isHeld()) {
2655 mWakeLock.release();
2656 }
2657 break;
2658 }
2659 }
2660 };
2661
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002662 // -------------------------------------------------------------------------
2663 // WebViewClient implementation.
2664 //-------------------------------------------------------------------------
2665
2666 // Use in overrideUrlLoading
2667 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2668 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2669 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2670 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2671
2672 /* package */ WebViewClient getWebViewClient() {
2673 return mWebViewClient;
2674 }
2675
The Android Open Source Projected217d92008-12-17 18:05:52 -08002676 private void updateIcon(String url, Bitmap icon) {
2677 if (icon != null) {
2678 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2679 url, icon);
2680 }
2681 setFavicon(icon);
2682 }
2683
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002684 private final WebViewClient mWebViewClient = new WebViewClient() {
2685 @Override
2686 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2687 resetLockIcon(url);
2688 setUrlTitle(url, null);
The Android Open Source Projected217d92008-12-17 18:05:52 -08002689 // Call updateIcon instead of setFavicon so the bookmark
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002690 // database can be updated.
The Android Open Source Projected217d92008-12-17 18:05:52 -08002691 updateIcon(url, favicon);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002692
2693 if (mSettings.isTracing() == true) {
2694 // FIXME: we should save the trace file somewhere other than data.
2695 // I can't use "/tmp" as it competes for system memory.
2696 File file = getDir("browserTrace", 0);
2697 String baseDir = file.getPath();
2698 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2699 String host;
2700 try {
2701 WebAddress uri = new WebAddress(url);
2702 host = uri.mHost;
2703 } catch (android.net.ParseException ex) {
2704 host = "unknown_host";
2705 }
2706 host = host.replace('.', '_');
2707 baseDir = baseDir + host;
2708 file = new File(baseDir+".data");
2709 if (file.exists() == true) {
2710 file.delete();
2711 }
2712 file = new File(baseDir+".key");
2713 if (file.exists() == true) {
2714 file.delete();
2715 }
2716 mInTrace = true;
2717 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2718 }
2719
2720 // Performance probe
2721 if (false) {
2722 mStart = SystemClock.uptimeMillis();
2723 mProcessStart = Process.getElapsedCpuTime();
2724 long[] sysCpu = new long[7];
2725 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2726 sysCpu, null)) {
2727 mUserStart = sysCpu[0] + sysCpu[1];
2728 mSystemStart = sysCpu[2];
2729 mIdleStart = sysCpu[3];
2730 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2731 }
2732 mUiStart = SystemClock.currentThreadTimeMillis();
2733 }
2734
2735 if (!mPageStarted) {
2736 mPageStarted = true;
2737 // if onResume() has been called, resumeWebView() does nothing.
2738 resumeWebView();
2739 }
2740
2741 // reset sync timer to avoid sync starts during loading a page
2742 CookieSyncManager.getInstance().resetSync();
2743
2744 mInLoad = true;
2745 updateInLoadMenuItems();
2746
2747 // schedule to check memory condition
2748 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
2749 CHECK_MEMORY_INTERVAL);
2750 }
2751
2752 @Override
2753 public void onPageFinished(WebView view, String url) {
2754 // Reset the title and icon in case we stopped a provisional
2755 // load.
2756 resetTitleAndIcon(view);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002757
2758 // Update the lock icon image only once we are done loading
2759 updateLockIconImage(mLockIconType);
2760
2761 // Performance probe
2762 if (false) {
2763 long[] sysCpu = new long[7];
2764 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2765 sysCpu, null)) {
2766 String uiInfo = "UI thread used "
2767 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2768 + " ms";
2769 if (Config.LOGD) {
2770 Log.d(LOGTAG, uiInfo);
2771 }
2772 //The string that gets written to the log
2773 String performanceString = "It took total "
2774 + (SystemClock.uptimeMillis() - mStart)
2775 + " ms clock time to load the page."
2776 + "\nbrowser process used "
2777 + (Process.getElapsedCpuTime() - mProcessStart)
2778 + " ms, user processes used "
2779 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2780 + " ms, kernel used "
2781 + (sysCpu[2] - mSystemStart) * 10
2782 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2783 + " ms and irq took "
2784 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2785 * 10 + " ms, " + uiInfo;
2786 if (Config.LOGD) {
2787 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2788 }
2789 if (url != null) {
2790 // strip the url to maintain consistency
2791 String newUrl = new String(url);
2792 if (newUrl.startsWith("http://www.")) {
2793 newUrl = newUrl.substring(11);
2794 } else if (newUrl.startsWith("http://")) {
2795 newUrl = newUrl.substring(7);
2796 } else if (newUrl.startsWith("https://www.")) {
2797 newUrl = newUrl.substring(12);
2798 } else if (newUrl.startsWith("https://")) {
2799 newUrl = newUrl.substring(8);
2800 }
2801 if (Config.LOGD) {
2802 Log.d(LOGTAG, newUrl + " loaded");
2803 }
2804 /*
2805 if (sWhiteList.contains(newUrl)) {
2806 // The string that gets pushed to the statistcs
2807 // service
2808 performanceString = performanceString
2809 + "\nWebpage: "
2810 + newUrl
2811 + "\nCarrier: "
2812 + android.os.SystemProperties
2813 .get("gsm.sim.operator.alpha");
2814 if (mWebView != null
2815 && mWebView.getContext() != null
2816 && mWebView.getContext().getSystemService(
2817 Context.CONNECTIVITY_SERVICE) != null) {
2818 ConnectivityManager cManager =
2819 (ConnectivityManager) mWebView
2820 .getContext().getSystemService(
2821 Context.CONNECTIVITY_SERVICE);
2822 NetworkInfo nInfo = cManager
2823 .getActiveNetworkInfo();
2824 if (nInfo != null) {
2825 performanceString = performanceString
2826 + "\nNetwork Type: "
2827 + nInfo.getType().toString();
2828 }
2829 }
2830 Checkin.logEvent(mResolver,
2831 Checkin.Events.Tag.WEBPAGE_LOAD,
2832 performanceString);
2833 Log.w(LOGTAG, "pushed to the statistics service");
2834 }
2835 */
2836 }
2837 }
2838 }
2839
2840 if (mInTrace) {
2841 mInTrace = false;
2842 Debug.stopMethodTracing();
2843 }
2844
2845 if (mPageStarted) {
2846 mPageStarted = false;
2847 // pauseWebView() will do nothing and return false if onPause()
2848 // is not called yet.
2849 if (pauseWebView()) {
2850 if (mWakeLock.isHeld()) {
2851 mHandler.removeMessages(RELEASE_WAKELOCK);
2852 mWakeLock.release();
2853 }
2854 }
2855 }
2856
2857 if (mInLoad) {
2858 mInLoad = false;
2859 updateInLoadMenuItems();
2860 }
2861
2862 mHandler.removeMessages(CHECK_MEMORY);
2863 checkMemory();
2864 }
2865
2866 // return true if want to hijack the url to let another app to handle it
2867 @Override
2868 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2869 if (url.startsWith(SCHEME_WTAI)) {
2870 // wtai://wp/mc;number
2871 // number=string(phone-number)
2872 if (url.startsWith(SCHEME_WTAI_MC)) {
2873 Intent intent = new Intent(Intent.ACTION_VIEW,
2874 Uri.parse(WebView.SCHEME_TEL +
2875 url.substring(SCHEME_WTAI_MC.length())));
2876 startActivity(intent);
2877 return true;
2878 }
2879 // wtai://wp/sd;dtmf
2880 // dtmf=string(dialstring)
2881 if (url.startsWith(SCHEME_WTAI_SD)) {
2882 // TODO
2883 // only send when there is active voice connection
2884 return false;
2885 }
2886 // wtai://wp/ap;number;name
2887 // number=string(phone-number)
2888 // name=string
2889 if (url.startsWith(SCHEME_WTAI_AP)) {
2890 // TODO
2891 return false;
2892 }
2893 }
2894
2895 Uri uri;
2896 try {
2897 uri = Uri.parse(url);
2898 } catch (IllegalArgumentException ex) {
2899 return false;
2900 }
2901
2902 // check whether other activities want to handle this url
2903 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
2904 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2905 try {
2906 if (startActivityIfNeeded(intent, -1)) {
2907 return true;
2908 }
2909 } catch (ActivityNotFoundException ex) {
2910 // ignore the error. If no application can handle the URL,
2911 // eg about:blank, assume the browser can handle it.
2912 }
2913
2914 if (mMenuIsDown) {
2915 openTab(url);
2916 closeOptionsMenu();
2917 return true;
2918 }
2919
2920 return false;
2921 }
2922
2923 /**
2924 * Updates the lock icon. This method is called when we discover another
2925 * resource to be loaded for this page (for example, javascript). While
2926 * we update the icon type, we do not update the lock icon itself until
2927 * we are done loading, it is slightly more secure this way.
2928 */
2929 @Override
2930 public void onLoadResource(WebView view, String url) {
2931 if (url != null && url.length() > 0) {
2932 // It is only if the page claims to be secure
2933 // that we may have to update the lock:
2934 if (mLockIconType == LOCK_ICON_SECURE) {
2935 // If NOT a 'safe' url, change the lock to mixed content!
2936 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2937 mLockIconType = LOCK_ICON_MIXED;
2938 if (Config.LOGV) {
2939 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2940 " updated lock icon to " + mLockIconType + " due to " + url);
2941 }
2942 }
2943 }
2944 }
2945 }
2946
2947 /**
2948 * Show the dialog, asking the user if they would like to continue after
2949 * an excessive number of HTTP redirects.
2950 */
2951 @Override
2952 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2953 final Message continueMsg) {
2954 new AlertDialog.Builder(BrowserActivity.this)
2955 .setTitle(R.string.browserFrameRedirect)
2956 .setMessage(R.string.browserFrame307Post)
2957 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2958 public void onClick(DialogInterface dialog, int which) {
2959 continueMsg.sendToTarget();
2960 }})
2961 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2962 public void onClick(DialogInterface dialog, int which) {
2963 cancelMsg.sendToTarget();
2964 }})
2965 .setOnCancelListener(new OnCancelListener() {
2966 public void onCancel(DialogInterface dialog) {
2967 cancelMsg.sendToTarget();
2968 }})
2969 .show();
2970 }
2971
2972 /**
2973 * Show a dialog informing the user of the network error reported by
2974 * WebCore.
2975 */
2976 @Override
2977 public void onReceivedError(WebView view, int errorCode,
2978 String description, String failingUrl) {
2979 if (errorCode != EventHandler.ERROR_LOOKUP &&
2980 errorCode != EventHandler.ERROR_CONNECT &&
2981 errorCode != EventHandler.ERROR_BAD_URL &&
The Android Open Source Projected217d92008-12-17 18:05:52 -08002982 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002983 errorCode != EventHandler.FILE_ERROR) {
2984 new AlertDialog.Builder(BrowserActivity.this)
2985 .setTitle((errorCode == EventHandler.FILE_NOT_FOUND_ERROR) ?
2986 R.string.browserFrameFileErrorLabel :
2987 R.string.browserFrameNetworkErrorLabel)
2988 .setMessage(description)
2989 .setPositiveButton(R.string.ok, null)
2990 .show();
2991 }
2992 Log.e(LOGTAG, "onReceivedError code:"+errorCode+" "+description);
2993
2994 // We need to reset the title after an error.
2995 resetTitleAndRevertLockIcon();
2996 }
2997
2998 /**
2999 * Check with the user if it is ok to resend POST data as the page they
3000 * are trying to navigate to is the result of a POST.
3001 */
3002 @Override
3003 public void onFormResubmission(WebView view, final Message dontResend,
3004 final Message resend) {
3005 new AlertDialog.Builder(BrowserActivity.this)
3006 .setTitle(R.string.browserFrameFormResubmitLabel)
3007 .setMessage(R.string.browserFrameFormResubmitMessage)
3008 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3009 public void onClick(DialogInterface dialog, int which) {
3010 resend.sendToTarget();
3011 }})
3012 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3013 public void onClick(DialogInterface dialog, int which) {
3014 dontResend.sendToTarget();
3015 }})
3016 .setOnCancelListener(new OnCancelListener() {
3017 public void onCancel(DialogInterface dialog) {
3018 dontResend.sendToTarget();
3019 }})
3020 .show();
3021 }
3022
3023 /**
3024 * Insert the url into the visited history database.
3025 * @param url The url to be inserted.
3026 * @param isReload True if this url is being reloaded.
3027 * FIXME: Not sure what to do when reloading the page.
3028 */
3029 @Override
3030 public void doUpdateVisitedHistory(WebView view, String url,
3031 boolean isReload) {
3032 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3033 return;
3034 }
3035 Browser.updateVisitedHistory(mResolver, url, true);
3036 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3037 }
3038
3039 /**
3040 * Displays SSL error(s) dialog to the user.
3041 */
3042 @Override
3043 public void onReceivedSslError(
3044 final WebView view, final SslErrorHandler handler, final SslError error) {
3045
3046 if (mSettings.showSecurityWarnings()) {
3047 final LayoutInflater factory =
3048 LayoutInflater.from(BrowserActivity.this);
3049 final View warningsView =
3050 factory.inflate(R.layout.ssl_warnings, null);
3051 final LinearLayout placeholder =
3052 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3053
3054 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3055 LinearLayout ll = (LinearLayout)factory
3056 .inflate(R.layout.ssl_warning, null);
3057 ((TextView)ll.findViewById(R.id.warning))
3058 .setText(R.string.ssl_untrusted);
3059 placeholder.addView(ll);
3060 }
3061
3062 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3063 LinearLayout ll = (LinearLayout)factory
3064 .inflate(R.layout.ssl_warning, null);
3065 ((TextView)ll.findViewById(R.id.warning))
3066 .setText(R.string.ssl_mismatch);
3067 placeholder.addView(ll);
3068 }
3069
3070 if (error.hasError(SslError.SSL_EXPIRED)) {
3071 LinearLayout ll = (LinearLayout)factory
3072 .inflate(R.layout.ssl_warning, null);
3073 ((TextView)ll.findViewById(R.id.warning))
3074 .setText(R.string.ssl_expired);
3075 placeholder.addView(ll);
3076 }
3077
3078 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3079 LinearLayout ll = (LinearLayout)factory
3080 .inflate(R.layout.ssl_warning, null);
3081 ((TextView)ll.findViewById(R.id.warning))
3082 .setText(R.string.ssl_not_yet_valid);
3083 placeholder.addView(ll);
3084 }
3085
3086 new AlertDialog.Builder(BrowserActivity.this)
3087 .setTitle(R.string.security_warning)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003088 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003089 .setView(warningsView)
3090 .setPositiveButton(R.string.ssl_continue,
3091 new DialogInterface.OnClickListener() {
3092 public void onClick(DialogInterface dialog, int whichButton) {
3093 handler.proceed();
3094 }
3095 })
3096 .setNeutralButton(R.string.view_certificate,
3097 new DialogInterface.OnClickListener() {
3098 public void onClick(DialogInterface dialog, int whichButton) {
3099 showSSLCertificateOnError(view, handler, error);
3100 }
3101 })
3102 .setNegativeButton(R.string.cancel,
3103 new DialogInterface.OnClickListener() {
3104 public void onClick(DialogInterface dialog, int whichButton) {
3105 handler.cancel();
3106 BrowserActivity.this.resetTitleAndRevertLockIcon();
3107 }
3108 })
3109 .setOnCancelListener(
3110 new DialogInterface.OnCancelListener() {
3111 public void onCancel(DialogInterface dialog) {
3112 handler.cancel();
3113 BrowserActivity.this.resetTitleAndRevertLockIcon();
3114 }
3115 })
3116 .show();
3117 } else {
3118 handler.proceed();
3119 }
3120 }
3121
3122 /**
3123 * Handles an HTTP authentication request.
3124 *
3125 * @param handler The authentication handler
3126 * @param host The host
3127 * @param realm The realm
3128 */
3129 @Override
3130 public void onReceivedHttpAuthRequest(WebView view,
3131 final HttpAuthHandler handler, final String host, final String realm) {
3132 String username = null;
3133 String password = null;
3134
3135 boolean reuseHttpAuthUsernamePassword =
3136 handler.useHttpAuthUsernamePassword();
3137
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003138 if (reuseHttpAuthUsernamePassword &&
3139 (mTabControl.getCurrentWebView() != null)) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003140 String[] credentials =
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003141 mTabControl.getCurrentWebView()
3142 .getHttpAuthUsernamePassword(host, realm);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003143 if (credentials != null && credentials.length == 2) {
3144 username = credentials[0];
3145 password = credentials[1];
3146 }
3147 }
3148
3149 if (username != null && password != null) {
3150 handler.proceed(username, password);
3151 } else {
3152 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3153 }
3154 }
3155
3156 @Override
3157 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3158 if (mMenuIsDown) {
3159 // only check shortcut key when MENU is held
3160 return getWindow().isShortcutKey(event.getKeyCode(), event);
3161 } else {
3162 return false;
3163 }
3164 }
3165
3166 @Override
3167 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003168 if (view != mTabControl.getCurrentTopWebView()) {
3169 return;
3170 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003171 if (event.isDown()) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003172 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003173 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003174 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003175 }
3176 }
3177 };
3178
3179 //--------------------------------------------------------------------------
3180 // WebChromeClient implementation
3181 //--------------------------------------------------------------------------
3182
3183 /* package */ WebChromeClient getWebChromeClient() {
3184 return mWebChromeClient;
3185 }
3186
3187 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3188 // Helper method to create a new tab or sub window.
3189 private void createWindow(final boolean dialog, final Message msg) {
3190 if (dialog) {
3191 mTabControl.createSubWindow();
3192 final TabControl.Tab t = mTabControl.getCurrentTab();
3193 attachSubWindow(t);
3194 WebView.WebViewTransport transport =
3195 (WebView.WebViewTransport) msg.obj;
3196 transport.setWebView(t.getSubWebView());
3197 msg.sendToTarget();
3198 } else {
3199 final TabControl.Tab parent = mTabControl.getCurrentTab();
3200 // openTabAndShow will dispatch the message after creating the
3201 // new WebView. This will prevent another request from coming
3202 // in during the animation.
The Android Open Source Projected217d92008-12-17 18:05:52 -08003203 openTabAndShow(null, msg, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003204 parent.addChildTab(mTabControl.getCurrentTab());
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003205 WebView.WebViewTransport transport =
3206 (WebView.WebViewTransport) msg.obj;
3207 transport.setWebView(mTabControl.getCurrentWebView());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003208 }
3209 }
3210
3211 @Override
3212 public boolean onCreateWindow(WebView view, final boolean dialog,
3213 final boolean userGesture, final Message resultMsg) {
3214 // Ignore these requests during tab animations or if the tab
3215 // overview is showing.
3216 if (mAnimationCount > 0 || mTabOverview != null) {
3217 return false;
3218 }
3219 // Short-circuit if we can't create any more tabs or sub windows.
3220 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3221 new AlertDialog.Builder(BrowserActivity.this)
3222 .setTitle(R.string.too_many_subwindows_dialog_title)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003223 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003224 .setMessage(R.string.too_many_subwindows_dialog_message)
3225 .setPositiveButton(R.string.ok, null)
3226 .show();
3227 return false;
3228 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3229 new AlertDialog.Builder(BrowserActivity.this)
3230 .setTitle(R.string.too_many_windows_dialog_title)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003231 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003232 .setMessage(R.string.too_many_windows_dialog_message)
3233 .setPositiveButton(R.string.ok, null)
3234 .show();
3235 return false;
3236 }
3237
3238 // Short-circuit if this was a user gesture.
3239 if (userGesture) {
3240 // createWindow will call openTabAndShow for new Windows and
3241 // that will call tabPicker which will increment
3242 // mAnimationCount.
3243 createWindow(dialog, resultMsg);
3244 return true;
3245 }
3246
3247 // Allow the popup and create the appropriate window.
3248 final AlertDialog.OnClickListener allowListener =
3249 new AlertDialog.OnClickListener() {
3250 public void onClick(DialogInterface d,
3251 int which) {
3252 // Same comment as above for setting
3253 // mAnimationCount.
3254 createWindow(dialog, resultMsg);
3255 // Since we incremented mAnimationCount while the
3256 // dialog was up, we have to decrement it here.
3257 mAnimationCount--;
3258 }
3259 };
3260
3261 // Block the popup by returning a null WebView.
3262 final AlertDialog.OnClickListener blockListener =
3263 new AlertDialog.OnClickListener() {
3264 public void onClick(DialogInterface d, int which) {
3265 resultMsg.sendToTarget();
3266 // We are not going to trigger an animation so
3267 // unblock keys and animation requests.
3268 mAnimationCount--;
3269 }
3270 };
3271
3272 // Build a confirmation dialog to display to the user.
3273 final AlertDialog d =
3274 new AlertDialog.Builder(BrowserActivity.this)
3275 .setTitle(R.string.attention)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003276 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003277 .setMessage(R.string.popup_window_attempt)
3278 .setPositiveButton(R.string.allow, allowListener)
3279 .setNegativeButton(R.string.block, blockListener)
3280 .setCancelable(false)
3281 .create();
3282
3283 // Show the confirmation dialog.
3284 d.show();
3285 // We want to increment mAnimationCount here to prevent a
3286 // potential race condition. If the user allows a pop-up from a
3287 // site and that pop-up then triggers another pop-up, it is
3288 // possible to get the BACK key between here and when the dialog
3289 // appears.
3290 mAnimationCount++;
3291 return true;
3292 }
3293
3294 @Override
3295 public void onCloseWindow(WebView window) {
3296 final int currentIndex = mTabControl.getCurrentIndex();
3297 final TabControl.Tab parent =
3298 mTabControl.getCurrentTab().getParentTab();
3299 if (parent != null) {
3300 // JavaScript can only close popup window.
The Android Open Source Projected217d92008-12-17 18:05:52 -08003301 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003302 }
3303 }
3304
3305 @Override
3306 public void onProgressChanged(WebView view, int newProgress) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003307 // Block progress updates to the title bar while the tab overview
3308 // is animating or being displayed.
3309 if (mAnimationCount == 0 && mTabOverview == null) {
3310 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3311 newProgress * 100);
3312 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003313
3314 if (newProgress == 100) {
3315 // onProgressChanged() is called for sub-frame too while
3316 // onPageFinished() is only called for the main frame. sync
3317 // cookie and cache promptly here.
3318 CookieSyncManager.getInstance().sync();
3319 }
3320 }
3321
3322 @Override
3323 public void onReceivedTitle(WebView view, String title) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003324 String url = view.getOriginalUrl();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003325
3326 // here, if url is null, we want to reset the title
3327 setUrlTitle(url, title);
3328
3329 if (url == null ||
3330 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3331 return;
3332 }
3333 if (url.startsWith("http://www.")) {
3334 url = url.substring(11);
3335 } else if (url.startsWith("http://")) {
3336 url = url.substring(4);
3337 }
3338 try {
3339 url = "%" + url;
3340 String [] selArgs = new String[] { url };
3341
3342 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3343 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3344 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3345 Browser.HISTORY_PROJECTION, where, selArgs, null);
3346 if (c.moveToFirst()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003347 if (Config.LOGV) {
3348 Log.v(LOGTAG, "updating cursor");
3349 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003350 // Current implementation of database only has one entry per
3351 // url.
3352 int titleIndex =
3353 c.getColumnIndex(Browser.BookmarkColumns.TITLE);
3354 c.updateString(titleIndex, title);
3355 c.commitUpdates();
3356 }
3357 c.close();
3358 } catch (IllegalStateException e) {
3359 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3360 } catch (SQLiteException ex) {
3361 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3362 }
3363 }
3364
3365 @Override
3366 public void onReceivedIcon(WebView view, Bitmap icon) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003367 updateIcon(view.getUrl(), icon);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003368 }
3369
3370 //----------------------------------------------------------------------
3371 // JavaScript functions.
3372 //----------------------------------------------------------------------
3373
3374 // Show an alert to the user.
3375 @Override
3376 public boolean onJsAlert(WebView view, String url, String message,
3377 JsResult result) {
3378 String title = url;
3379 if (URLUtil.isDataUrl(url)) {
3380 // For data: urls, we just display 'JavaScript' similar to
3381 // Safari.
3382 title = getString(R.string.js_dialog_title_default);
3383 } else {
3384 try {
3385 URL aUrl = new URL(url);
3386 // Example: "The page at 'http://www.mit.edu' says:"
3387 title = getText(R.string.js_dialog_title_prefix)
3388 + " '"
3389 + (aUrl.getProtocol() + "://" + aUrl.getHost())
3390 + "' "
3391 + getText(R.string.js_dialog_title_suffix);
3392 } catch (MalformedURLException ex) {
3393 // do nothing. just use the url passed as the title
3394 }
3395 }
3396 final JsResult res = result;
3397 new AlertDialog.Builder(BrowserActivity.this)
3398 .setTitle(title)
3399 .setMessage(message)
3400 .setPositiveButton(R.string.ok,
3401 new AlertDialog.OnClickListener() {
3402 public void onClick(DialogInterface dialog,
3403 int which) {
3404 res.confirm();
3405 }
3406 })
3407 .setCancelable(false)
3408 .show();
3409 return true;
3410 }
3411
3412 @Override
3413 public boolean onJsConfirm(WebView view, String url, String message,
3414 final JsResult result) {
3415 String title = url;
3416 try {
3417 URL aUrl = new URL(url);
3418 // Example: "The page at 'http://www.mit.edu' says:"
3419 title = getText(R.string.js_dialog_title_prefix)
3420 + " '"
3421 + (aUrl.getProtocol() + "://" + aUrl.getHost())
3422 + "' "
3423 + getText(R.string.js_dialog_title_suffix);
3424 } catch (MalformedURLException ex) {
3425 // do nothing. just use the url passed as the title
3426 }
3427 new AlertDialog.Builder(BrowserActivity.this)
3428 .setTitle(title)
3429 .setMessage(message)
3430 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3431 public void onClick(DialogInterface dialog, int which) {
3432 mHandler.obtainMessage(JS_CONFIRM, 1, 0, result).sendToTarget();
3433 }})
3434 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3435 public void onClick(DialogInterface dialog, int which) {
3436 mHandler.obtainMessage(JS_CONFIRM, 0, 0, result).sendToTarget();
3437 }})
3438 .show();
3439 // Return true so WebView knows we will handle the confirm.
3440 return true;
3441 }
3442
3443 @Override
3444 public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
3445 final JsPromptResult result) {
3446 String title = url;
3447 try {
3448 URL aUrl = new URL(url);
3449 // Example: "The page at 'http://www.mit.edu' says:"
3450 title = getText(R.string.js_dialog_title_prefix)
3451 + " '"
3452 + (aUrl.getProtocol() + "://" + aUrl.getHost())
3453 + "' "
3454 + getText(R.string.js_dialog_title_suffix);
3455 } catch (MalformedURLException ex) {
3456 // do nothing, just use the url passed as the title
3457 }
3458
3459 final LayoutInflater factory = LayoutInflater.from(BrowserActivity.this);
3460 final View v = factory.inflate(R.layout.js_prompt, null);
3461 ((TextView)v.findViewById(R.id.message)).setText(message);
3462 ((EditText)v.findViewById(R.id.value)).setText(defaultValue);
3463
3464 new AlertDialog.Builder(BrowserActivity.this)
3465 .setTitle(title)
3466 .setView(v)
3467 .setPositiveButton(R.string.ok,
3468 new DialogInterface.OnClickListener() {
3469 public void onClick(DialogInterface dialog, int whichButton) {
3470 String value = ((EditText)v.findViewById(R.id.value)).getText()
3471 .toString();
3472 result.confirm(value);
3473 }
3474 })
3475 .setNegativeButton(R.string.cancel,
3476 new DialogInterface.OnClickListener() {
3477 public void onClick(DialogInterface dialog, int whichButton) {
3478 result.cancel();
3479 }
3480 })
3481 .setOnCancelListener(
3482 new DialogInterface.OnCancelListener() {
3483 public void onCancel(DialogInterface dialog) {
3484 result.cancel();
3485 }
3486 })
3487 .show();
3488
3489 // Return true so WebView knows we will handle the prompt.
3490 return true;
3491 }
3492
3493 @Override
3494 public boolean onJsBeforeUnload(WebView view, String url,
3495 String message, final JsResult result) {
3496 final String m =
3497 getString(R.string.js_dialog_before_unload, message);
3498 new AlertDialog.Builder(BrowserActivity.this)
3499 .setMessage(m)
3500 .setPositiveButton(R.string.ok,
3501 new DialogInterface.OnClickListener() {
3502 public void onClick(DialogInterface dialog,
3503 int which) {
3504 // Use JS_CONFIRM since it has the same
3505 // behavior we want here.
3506 mHandler.obtainMessage(JS_CONFIRM, 1, 0,
3507 result).sendToTarget();
3508 }})
3509 .setNegativeButton(R.string.cancel,
3510 new DialogInterface.OnClickListener() {
3511 public void onClick(DialogInterface dialog,
3512 int which) {
3513 // Use JS_CONFIRM since it has the same
3514 // behavior we want here.
3515 mHandler.obtainMessage(JS_CONFIRM, 0, 0,
3516 result).sendToTarget();
3517 }})
3518 .show();
3519 // Return true so WebView knows we will handle the dialog.
3520 return true;
3521 }
3522 };
3523
3524 /**
3525 * Notify the host application a download should be done, or that
3526 * the data should be streamed if a streaming viewer is available.
3527 * @param url The full url to the content that should be downloaded
3528 * @param contentDisposition Content-disposition http header, if
3529 * present.
3530 * @param mimetype The mimetype of the content reported by the server
3531 * @param contentLength The file size reported by the server
3532 */
3533 public void onDownloadStart(String url, String userAgent,
3534 String contentDisposition, String mimetype, long contentLength) {
3535 // if we're dealing wih A/V content that's not explicitly marked
3536 // for download, check if it's streamable.
3537 if (contentDisposition == null
3538 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3539 // query the package manager to see if there's a registered handler
3540 // that matches.
3541 Intent intent = new Intent(Intent.ACTION_VIEW);
3542 intent.setDataAndType(Uri.parse(url), mimetype);
3543 if (getPackageManager().queryIntentActivities(intent,
3544 PackageManager.MATCH_DEFAULT_ONLY).size() != 0) {
3545 // someone knows how to handle this mime type with this scheme, don't download.
3546 try {
3547 startActivity(intent);
3548 return;
3549 } catch (ActivityNotFoundException ex) {
3550 if (Config.LOGD) {
3551 Log.d(LOGTAG, "activity not found for " + mimetype
3552 + " over " + Uri.parse(url).getScheme(), ex);
3553 }
3554 // Best behavior is to fall back to a download in this case
3555 }
3556 }
3557 }
3558 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3559 }
3560
3561 /**
3562 * Notify the host application a download should be done, even if there
3563 * is a streaming viewer available for thise type.
3564 * @param url The full url to the content that should be downloaded
3565 * @param contentDisposition Content-disposition http header, if
3566 * present.
3567 * @param mimetype The mimetype of the content reported by the server
3568 * @param contentLength The file size reported by the server
3569 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08003570 /*package */ void onDownloadStartNoStream(String url, String userAgent,
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003571 String contentDisposition, String mimetype, long contentLength) {
3572
3573 String filename = URLUtil.guessFileName(url,
3574 contentDisposition, mimetype);
3575
3576 // Check to see if we have an SDCard
The Android Open Source Projected217d92008-12-17 18:05:52 -08003577 String status = Environment.getExternalStorageState();
3578 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3579 int title;
3580 String msg;
3581
3582 // Check to see if the SDCard is busy, same as the music app
3583 if (status.equals(Environment.MEDIA_SHARED)) {
3584 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3585 title = R.string.download_sdcard_busy_dlg_title;
3586 } else {
3587 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3588 title = R.string.download_no_sdcard_dlg_title;
3589 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003590
3591 new AlertDialog.Builder(this)
The Android Open Source Projected217d92008-12-17 18:05:52 -08003592 .setTitle(title)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003593 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003594 .setMessage(msg)
3595 .setPositiveButton(R.string.ok, null)
3596 .show();
3597 return;
3598 }
3599
3600 String cookies = CookieManager.getInstance().getCookie(url);
3601
3602 ContentValues values = new ContentValues();
3603 values.put(Downloads.URI, url);
3604 values.put(Downloads.COOKIE_DATA, cookies);
3605 values.put(Downloads.USER_AGENT, userAgent);
3606 values.put(Downloads.NOTIFICATION_PACKAGE,
3607 getPackageName());
3608 values.put(Downloads.NOTIFICATION_CLASS,
3609 BrowserDownloadPage.class.getCanonicalName());
3610 values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3611 values.put(Downloads.MIMETYPE, mimetype);
3612 values.put(Downloads.FILENAME_HINT, filename);
3613 values.put(Downloads.DESCRIPTION, Uri.parse(url).getHost());
3614 if (contentLength > 0) {
3615 values.put(Downloads.TOTAL_BYTES, contentLength);
3616 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08003617 if (mimetype == null) {
3618 // We must have long pressed on a link or image to download it. We
3619 // are not sure of the mimetype in this case, so do a head request
3620 new FetchUrlMimeType(this).execute(values);
3621 } else {
3622 final Uri contentUri =
3623 getContentResolver().insert(Downloads.CONTENT_URI, values);
3624 viewDownloads(contentUri);
3625 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003626
3627 }
3628
3629 /**
3630 * Resets the lock icon. This method is called when we start a new load and
3631 * know the url to be loaded.
3632 */
3633 private void resetLockIcon(String url) {
3634 // Save the lock-icon state (we revert to it if the load gets cancelled)
3635 saveLockIcon();
3636
3637 mLockIconType = LOCK_ICON_UNSECURE;
3638 if (URLUtil.isHttpsUrl(url)) {
3639 mLockIconType = LOCK_ICON_SECURE;
3640 if (Config.LOGV) {
3641 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3642 " reset lock icon to " + mLockIconType);
3643 }
3644 }
3645
3646 updateLockIconImage(LOCK_ICON_UNSECURE);
3647 }
3648
3649 /**
3650 * Resets the lock icon. This method is called when the icon needs to be
3651 * reset but we do not know whether we are loading a secure or not secure
3652 * page.
3653 */
3654 private void resetLockIcon() {
3655 // Save the lock-icon state (we revert to it if the load gets cancelled)
3656 saveLockIcon();
3657
3658 mLockIconType = LOCK_ICON_UNSECURE;
3659
3660 if (Config.LOGV) {
3661 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3662 " reset lock icon to " + mLockIconType);
3663 }
3664
3665 updateLockIconImage(LOCK_ICON_UNSECURE);
3666 }
3667
3668 /**
3669 * Updates the lock-icon image in the title-bar.
3670 */
3671 private void updateLockIconImage(int lockIconType) {
3672 Drawable d = null;
3673 if (lockIconType == LOCK_ICON_SECURE) {
3674 d = mSecLockIcon;
3675 } else if (lockIconType == LOCK_ICON_MIXED) {
3676 d = mMixLockIcon;
3677 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08003678 // If the tab overview is animating or being shown, do not update the
3679 // lock icon.
3680 if (mAnimationCount == 0 && mTabOverview == null) {
3681 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
3682 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003683 }
3684
3685 /**
3686 * Displays a page-info dialog.
The Android Open Source Projected217d92008-12-17 18:05:52 -08003687 * @param tab The tab to show info about
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003688 * @param fromShowSSLCertificateOnError The flag that indicates whether
3689 * this dialog was opened from the SSL-certificate-on-error dialog or
3690 * not. This is important, since we need to know whether to return to
3691 * the parent dialog or simply dismiss.
3692 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08003693 private void showPageInfo(final TabControl.Tab tab,
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003694 final boolean fromShowSSLCertificateOnError) {
3695 final LayoutInflater factory = LayoutInflater
3696 .from(this);
3697
3698 final View pageInfoView = factory.inflate(R.layout.page_info, null);
The Android Open Source Projected217d92008-12-17 18:05:52 -08003699
3700 final WebView view = tab.getWebView();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003701
3702 String url = null;
3703 String title = null;
3704
The Android Open Source Projected217d92008-12-17 18:05:52 -08003705 if (view == null) {
3706 url = tab.getUrl();
3707 title = tab.getTitle();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003708 } else if (view == mTabControl.getCurrentWebView()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003709 // Use the cached title and url if this is the current WebView
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003710 url = mUrl;
3711 title = mTitle;
3712 } else {
3713 url = view.getUrl();
3714 title = view.getTitle();
3715 }
3716
3717 if (url == null) {
3718 url = "";
3719 }
3720 if (title == null) {
3721 title = "";
3722 }
3723
3724 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3725 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3726
The Android Open Source Projected217d92008-12-17 18:05:52 -08003727 mPageInfoView = tab;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003728 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3729
3730 AlertDialog.Builder alertDialogBuilder =
3731 new AlertDialog.Builder(this)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003732 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003733 .setView(pageInfoView)
3734 .setPositiveButton(
3735 R.string.ok,
3736 new DialogInterface.OnClickListener() {
3737 public void onClick(DialogInterface dialog,
3738 int whichButton) {
3739 mPageInfoDialog = null;
3740 mPageInfoView = null;
3741 mPageInfoFromShowSSLCertificateOnError = null;
3742
3743 // if we came here from the SSL error dialog
3744 if (fromShowSSLCertificateOnError) {
3745 // go back to the SSL error dialog
3746 showSSLCertificateOnError(
3747 mSSLCertificateOnErrorView,
3748 mSSLCertificateOnErrorHandler,
3749 mSSLCertificateOnErrorError);
3750 }
3751 }
3752 })
3753 .setOnCancelListener(
3754 new DialogInterface.OnCancelListener() {
3755 public void onCancel(DialogInterface dialog) {
3756 mPageInfoDialog = null;
3757 mPageInfoView = null;
3758 mPageInfoFromShowSSLCertificateOnError = null;
3759
3760 // if we came here from the SSL error dialog
3761 if (fromShowSSLCertificateOnError) {
3762 // go back to the SSL error dialog
3763 showSSLCertificateOnError(
3764 mSSLCertificateOnErrorView,
3765 mSSLCertificateOnErrorHandler,
3766 mSSLCertificateOnErrorError);
3767 }
3768 }
3769 });
3770
3771 // if we have a main top-level page SSL certificate set or a certificate
3772 // error
The Android Open Source Projected217d92008-12-17 18:05:52 -08003773 if (fromShowSSLCertificateOnError ||
3774 (view != null && view.getCertificate() != null)) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003775 // add a 'View Certificate' button
3776 alertDialogBuilder.setNeutralButton(
3777 R.string.view_certificate,
3778 new DialogInterface.OnClickListener() {
3779 public void onClick(DialogInterface dialog,
3780 int whichButton) {
3781 mPageInfoDialog = null;
3782 mPageInfoView = null;
3783 mPageInfoFromShowSSLCertificateOnError = null;
3784
3785 // if we came here from the SSL error dialog
3786 if (fromShowSSLCertificateOnError) {
3787 // go back to the SSL error dialog
3788 showSSLCertificateOnError(
3789 mSSLCertificateOnErrorView,
3790 mSSLCertificateOnErrorHandler,
3791 mSSLCertificateOnErrorError);
3792 } else {
3793 // otherwise, display the top-most certificate from
3794 // the chain
3795 if (view.getCertificate() != null) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003796 showSSLCertificate(tab);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003797 }
3798 }
3799 }
3800 });
3801 }
3802
3803 mPageInfoDialog = alertDialogBuilder.show();
3804 }
3805
3806 /**
3807 * Displays the main top-level page SSL certificate dialog
3808 * (accessible from the Page-Info dialog).
The Android Open Source Projected217d92008-12-17 18:05:52 -08003809 * @param tab The tab to show certificate for.
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003810 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08003811 private void showSSLCertificate(final TabControl.Tab tab) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003812 final View certificateView =
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003813 inflateCertificateView(tab.getWebView().getCertificate());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003814 if (certificateView == null) {
3815 return;
3816 }
3817
3818 LayoutInflater factory = LayoutInflater.from(this);
3819
3820 final LinearLayout placeholder =
3821 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3822
3823 LinearLayout ll = (LinearLayout) factory.inflate(
3824 R.layout.ssl_success, placeholder);
3825 ((TextView)ll.findViewById(R.id.success))
3826 .setText(R.string.ssl_certificate_is_valid);
3827
The Android Open Source Projected217d92008-12-17 18:05:52 -08003828 mSSLCertificateView = tab;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003829 mSSLCertificateDialog =
3830 new AlertDialog.Builder(this)
3831 .setTitle(R.string.ssl_certificate).setIcon(
3832 R.drawable.ic_dialog_browser_certificate_secure)
3833 .setView(certificateView)
3834 .setPositiveButton(R.string.ok,
3835 new DialogInterface.OnClickListener() {
3836 public void onClick(DialogInterface dialog,
3837 int whichButton) {
3838 mSSLCertificateDialog = null;
3839 mSSLCertificateView = null;
3840
The Android Open Source Projected217d92008-12-17 18:05:52 -08003841 showPageInfo(tab, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003842 }
3843 })
3844 .setOnCancelListener(
3845 new DialogInterface.OnCancelListener() {
3846 public void onCancel(DialogInterface dialog) {
3847 mSSLCertificateDialog = null;
3848 mSSLCertificateView = null;
3849
The Android Open Source Projected217d92008-12-17 18:05:52 -08003850 showPageInfo(tab, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003851 }
3852 })
3853 .show();
3854 }
3855
3856 /**
3857 * Displays the SSL error certificate dialog.
3858 * @param view The target web-view.
3859 * @param handler The SSL error handler responsible for cancelling the
3860 * connection that resulted in an SSL error or proceeding per user request.
3861 * @param error The SSL error object.
3862 */
3863 private void showSSLCertificateOnError(
3864 final WebView view, final SslErrorHandler handler, final SslError error) {
3865
3866 final View certificateView =
3867 inflateCertificateView(error.getCertificate());
3868 if (certificateView == null) {
3869 return;
3870 }
3871
3872 LayoutInflater factory = LayoutInflater.from(this);
3873
3874 final LinearLayout placeholder =
3875 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3876
3877 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3878 LinearLayout ll = (LinearLayout)factory
3879 .inflate(R.layout.ssl_warning, placeholder);
3880 ((TextView)ll.findViewById(R.id.warning))
3881 .setText(R.string.ssl_untrusted);
3882 }
3883
3884 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3885 LinearLayout ll = (LinearLayout)factory
3886 .inflate(R.layout.ssl_warning, placeholder);
3887 ((TextView)ll.findViewById(R.id.warning))
3888 .setText(R.string.ssl_mismatch);
3889 }
3890
3891 if (error.hasError(SslError.SSL_EXPIRED)) {
3892 LinearLayout ll = (LinearLayout)factory
3893 .inflate(R.layout.ssl_warning, placeholder);
3894 ((TextView)ll.findViewById(R.id.warning))
3895 .setText(R.string.ssl_expired);
3896 }
3897
3898 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3899 LinearLayout ll = (LinearLayout)factory
3900 .inflate(R.layout.ssl_warning, placeholder);
3901 ((TextView)ll.findViewById(R.id.warning))
3902 .setText(R.string.ssl_not_yet_valid);
3903 }
3904
3905 mSSLCertificateOnErrorHandler = handler;
3906 mSSLCertificateOnErrorView = view;
3907 mSSLCertificateOnErrorError = error;
3908 mSSLCertificateOnErrorDialog =
3909 new AlertDialog.Builder(this)
3910 .setTitle(R.string.ssl_certificate).setIcon(
3911 R.drawable.ic_dialog_browser_certificate_partially_secure)
3912 .setView(certificateView)
3913 .setPositiveButton(R.string.ok,
3914 new DialogInterface.OnClickListener() {
3915 public void onClick(DialogInterface dialog,
3916 int whichButton) {
3917 mSSLCertificateOnErrorDialog = null;
3918 mSSLCertificateOnErrorView = null;
3919 mSSLCertificateOnErrorHandler = null;
3920 mSSLCertificateOnErrorError = null;
3921
3922 mWebViewClient.onReceivedSslError(
3923 view, handler, error);
3924 }
3925 })
3926 .setNeutralButton(R.string.page_info_view,
3927 new DialogInterface.OnClickListener() {
3928 public void onClick(DialogInterface dialog,
3929 int whichButton) {
3930 mSSLCertificateOnErrorDialog = null;
3931
3932 // do not clear the dialog state: we will
3933 // need to show the dialog again once the
3934 // user is done exploring the page-info details
3935
The Android Open Source Projected217d92008-12-17 18:05:52 -08003936 showPageInfo(mTabControl.getTabFromView(view),
3937 true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003938 }
3939 })
3940 .setOnCancelListener(
3941 new DialogInterface.OnCancelListener() {
3942 public void onCancel(DialogInterface dialog) {
3943 mSSLCertificateOnErrorDialog = null;
3944 mSSLCertificateOnErrorView = null;
3945 mSSLCertificateOnErrorHandler = null;
3946 mSSLCertificateOnErrorError = null;
3947
3948 mWebViewClient.onReceivedSslError(
3949 view, handler, error);
3950 }
3951 })
3952 .show();
3953 }
3954
3955 /**
3956 * Inflates the SSL certificate view (helper method).
3957 * @param certificate The SSL certificate.
3958 * @return The resultant certificate view with issued-to, issued-by,
3959 * issued-on, expires-on, and possibly other fields set.
3960 * If the input certificate is null, returns null.
3961 */
3962 private View inflateCertificateView(SslCertificate certificate) {
3963 if (certificate == null) {
3964 return null;
3965 }
3966
3967 LayoutInflater factory = LayoutInflater.from(this);
3968
3969 View certificateView = factory.inflate(
3970 R.layout.ssl_certificate, null);
3971
3972 // issued to:
3973 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3974 if (issuedTo != null) {
3975 ((TextView) certificateView.findViewById(R.id.to_common))
3976 .setText(issuedTo.getCName());
3977 ((TextView) certificateView.findViewById(R.id.to_org))
3978 .setText(issuedTo.getOName());
3979 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3980 .setText(issuedTo.getUName());
3981 }
3982
3983 // issued by:
3984 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3985 if (issuedBy != null) {
3986 ((TextView) certificateView.findViewById(R.id.by_common))
3987 .setText(issuedBy.getCName());
3988 ((TextView) certificateView.findViewById(R.id.by_org))
3989 .setText(issuedBy.getOName());
3990 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3991 .setText(issuedBy.getUName());
3992 }
3993
3994 // issued on:
3995 String issuedOn = reformatCertificateDate(
3996 certificate.getValidNotBefore());
3997 ((TextView) certificateView.findViewById(R.id.issued_on))
3998 .setText(issuedOn);
3999
4000 // expires on:
4001 String expiresOn = reformatCertificateDate(
4002 certificate.getValidNotAfter());
4003 ((TextView) certificateView.findViewById(R.id.expires_on))
4004 .setText(expiresOn);
4005
4006 return certificateView;
4007 }
4008
4009 /**
4010 * Re-formats the certificate date (Date.toString()) string to
4011 * a properly localized date string.
4012 * @return Properly localized version of the certificate date string and
4013 * the original certificate date string if fails to localize.
4014 * If the original string is null, returns an empty string "".
4015 */
4016 private String reformatCertificateDate(String certificateDate) {
4017 String reformattedDate = null;
4018
4019 if (certificateDate != null) {
4020 Date date = null;
4021 try {
4022 date = java.text.DateFormat.getInstance().parse(certificateDate);
4023 } catch (ParseException e) {
4024 date = null;
4025 }
4026
4027 if (date != null) {
4028 reformattedDate =
4029 DateFormat.getDateFormat(this).format(date);
4030 }
4031 }
4032
4033 return reformattedDate != null ? reformattedDate :
4034 (certificateDate != null ? certificateDate : "");
4035 }
4036
4037 /**
4038 * Displays an http-authentication dialog.
4039 */
4040 private void showHttpAuthentication(final HttpAuthHandler handler,
4041 final String host, final String realm, final String title,
4042 final String name, final String password, int focusId) {
4043 LayoutInflater factory = LayoutInflater.from(this);
4044 final View v = factory
4045 .inflate(R.layout.http_authentication, null);
4046 if (name != null) {
4047 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4048 }
4049 if (password != null) {
4050 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4051 }
4052
4053 String titleText = title;
4054 if (titleText == null) {
4055 titleText = getText(R.string.sign_in_to).toString().replace(
4056 "%s1", host).replace("%s2", realm);
4057 }
4058
4059 mHttpAuthHandler = handler;
4060 mHttpAuthenticationDialog = new AlertDialog.Builder(this)
4061 .setTitle(titleText)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004062 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004063 .setView(v)
4064 .setPositiveButton(R.string.action,
4065 new DialogInterface.OnClickListener() {
4066 public void onClick(DialogInterface dialog,
4067 int whichButton) {
4068 String nm = ((EditText) v
4069 .findViewById(R.id.username_edit))
4070 .getText().toString();
4071 String pw = ((EditText) v
4072 .findViewById(R.id.password_edit))
4073 .getText().toString();
4074 BrowserActivity.this.setHttpAuthUsernamePassword
4075 (host, realm, nm, pw);
4076 handler.proceed(nm, pw);
4077 mHttpAuthenticationDialog = null;
4078 mHttpAuthHandler = null;
4079 }})
4080 .setNegativeButton(R.string.cancel,
4081 new DialogInterface.OnClickListener() {
4082 public void onClick(DialogInterface dialog,
4083 int whichButton) {
4084 handler.cancel();
4085 BrowserActivity.this.resetTitleAndRevertLockIcon();
4086 mHttpAuthenticationDialog = null;
4087 mHttpAuthHandler = null;
4088 }})
4089 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4090 public void onCancel(DialogInterface dialog) {
4091 handler.cancel();
4092 BrowserActivity.this.resetTitleAndRevertLockIcon();
4093 mHttpAuthenticationDialog = null;
4094 mHttpAuthHandler = null;
4095 }})
4096 .show();
4097 if (focusId != 0) {
4098 mHttpAuthenticationDialog.findViewById(focusId).requestFocus();
4099 } else {
4100 v.findViewById(R.id.username_edit).requestFocus();
4101 }
4102 }
4103
4104 public int getProgress() {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004105 WebView w = mTabControl.getCurrentWebView();
4106 if (w != null) {
4107 return w.getProgress();
4108 } else {
4109 return 100;
4110 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004111 }
4112
4113 /**
4114 * Set HTTP authentication password.
4115 *
4116 * @param host The host for the password
4117 * @param realm The realm for the password
4118 * @param username The username for the password. If it is null, it means
4119 * password can't be saved.
4120 * @param password The password
4121 */
4122 public void setHttpAuthUsernamePassword(String host, String realm,
4123 String username,
4124 String password) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004125 WebView w = mTabControl.getCurrentWebView();
4126 if (w != null) {
4127 w.setHttpAuthUsernamePassword(host, realm, username, password);
4128 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004129 }
4130
4131 /**
4132 * http stack says net has come or gone... inform the user
4133 * @param up true if net has come up, false if net has gone down
4134 */
4135 public void onNetworkToggle(boolean up) {
4136 if (up) {
4137 if (mAlertDialog != null) {
4138 mAlertDialog.cancel();
4139 mAlertDialog = null;
4140 }
4141 } else {
4142 if (mInLoad && mAlertDialog == null) {
4143 mAlertDialog = new AlertDialog.Builder(this)
4144 .setTitle(R.string.loadSuspendedTitle)
4145 .setMessage(R.string.loadSuspended)
4146 .setPositiveButton(R.string.ok, null)
4147 .show();
4148 }
4149 }
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004150 WebView w = mTabControl.getCurrentWebView();
4151 if (w != null) {
4152 w.setNetworkAvailable(up);
4153 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004154 }
4155
4156 @Override
4157 protected void onActivityResult(int requestCode, int resultCode,
4158 Intent intent) {
4159 switch (requestCode) {
4160 case BOOKMARKS_PAGE:
4161 case CLASSIC_HISTORY_PAGE:
4162 if (resultCode == RESULT_OK && intent != null) {
4163 String data = intent.getAction();
4164 Bundle extras = intent.getExtras();
4165 if (extras != null && extras.getBoolean("new_window", false)) {
4166 openTab(data);
4167 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004168 final TabControl.Tab currentTab =
4169 mTabControl.getCurrentTab();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004170 // If the Window overview is up and we are not in the
4171 // middle of an animation, animate away from it to the
4172 // current tab.
4173 if (mTabOverview != null && mAnimationCount == 0) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004174 sendAnimateFromOverview(currentTab, false, data,
4175 TAB_OVERVIEW_DELAY, null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004176 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004177 dismissSubWindow(currentTab);
4178 if (data != null && data.length() != 0) {
4179 getTopWindow().loadUrl(data);
4180 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004181 }
4182 }
4183 }
4184 break;
4185 default:
4186 break;
4187 }
4188 getTopWindow().requestFocus();
4189 }
4190
4191 /*
4192 * This method is called as a result of the user selecting the options
4193 * menu to see the download window, or when a download changes state. It
4194 * shows the download window ontop of the current window.
4195 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08004196 /* package */ void viewDownloads(Uri downloadRecord) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004197 Intent intent = new Intent(this,
4198 BrowserDownloadPage.class);
4199 intent.setData(downloadRecord);
4200 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4201
4202 }
4203
4204 /**
4205 * Handle results from Tab Switcher mTabOverview tool
4206 */
4207 private class TabListener implements ImageGrid.Listener {
4208 public void remove(int position) {
4209 // Note: Remove is not enabled if we have only one tab.
4210 if (Config.DEBUG && mTabControl.getTabCount() == 1) {
4211 throw new AssertionError();
4212 }
4213
The Android Open Source Projected217d92008-12-17 18:05:52 -08004214 // Remember the current tab.
4215 TabControl.Tab current = mTabControl.getCurrentTab();
4216 final TabControl.Tab remove = mTabControl.getTab(position);
4217 mTabControl.removeTab(remove);
4218 // If we removed the current tab, use the tab at position - 1 if
4219 // possible.
4220 if (current == remove) {
4221 // If the user removes the last tab, act like the New Tab item
4222 // was clicked on.
4223 if (mTabControl.getTabCount() == 0) {
4224 current = mTabControl.createNewTab(false);
4225 sendAnimateFromOverview(current, true,
4226 mSettings.getHomePage(), TAB_OVERVIEW_DELAY, null);
4227 } else {
4228 final int index = position > 0 ? (position - 1) : 0;
4229 current = mTabControl.getTab(index);
4230 }
4231 }
4232
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004233 // The tab overview could have been dismissed before this method is
4234 // called.
4235 if (mTabOverview != null) {
4236 // Remove the tab and change the index.
The Android Open Source Projected217d92008-12-17 18:05:52 -08004237 mTabOverview.remove(position);
4238 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004239 }
4240
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004241 // Only the current tab ensures its WebView is non-null. This
4242 // implies that we are reloading the freed tab.
The Android Open Source Projected217d92008-12-17 18:05:52 -08004243 mTabControl.setCurrentTab(current);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004244 }
4245 public void onClick(int index) {
4246 // Change the tab if necessary.
4247 // Index equals ImageGrid.CANCEL when pressing back from the tab
4248 // overview.
4249 if (index == ImageGrid.CANCEL) {
4250 index = mTabControl.getCurrentIndex();
4251 // The current index is -1 if the current tab was removed.
4252 if (index == -1) {
4253 // Take the last tab as a fallback.
4254 index = mTabControl.getTabCount() - 1;
4255 }
4256 }
4257
4258 // Clear all the data for tab picker so next time it will be
4259 // recreated.
4260 mTabControl.wipeAllPickerData();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004261
4262 // NEW_TAB means that the "New Tab" cell was clicked on.
4263 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004264 openTabAndShow(mSettings.getHomePage(), null, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004265 } else {
4266 sendAnimateFromOverview(mTabControl.getTab(index),
4267 false, null, 0, null);
4268 }
4269 }
4270 }
4271
4272 // A fake View that draws the WebView's picture with a fast zoom filter.
4273 // The View is used in case the tab is freed during the animation because
4274 // of low memory.
4275 private static class AnimatingView extends View {
4276 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4277 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4278 private static final DrawFilter sZoomFilter =
4279 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4280 private final Picture mPicture;
4281 private final float mScale;
4282 private final int mScrollX;
4283 private final int mScrollY;
4284 final TabControl.Tab mTab;
4285
4286 AnimatingView(Context ctxt, TabControl.Tab t) {
4287 super(ctxt);
4288 mTab = t;
4289 // Use the top window in the animation since the tab overview will
4290 // display the top window in each cell.
4291 final WebView w = t.getTopWindow();
4292 mPicture = w.capturePicture();
4293 mScale = w.getScale() / w.getWidth();
4294 mScrollX = w.getScrollX();
4295 mScrollY = w.getScrollY();
4296 }
4297
4298 @Override
4299 protected void onDraw(Canvas canvas) {
4300 canvas.save();
4301 canvas.drawColor(Color.WHITE);
The Android Open Source Projected217d92008-12-17 18:05:52 -08004302 if (mPicture != null) {
4303 canvas.setDrawFilter(sZoomFilter);
4304 float scale = getWidth() * mScale;
4305 canvas.scale(scale, scale);
4306 canvas.translate(-mScrollX, -mScrollY);
4307 canvas.drawPicture(mPicture);
4308 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004309 canvas.restore();
4310 }
4311 }
4312
4313 /**
4314 * Open the tab picker. This function will always use the current tab in
4315 * its animation.
4316 * @param stay boolean stating whether the tab picker is to remain open
4317 * (in which case it needs a listener and its menu) or not.
4318 * @param index The index of the tab to show as the selection in the tab
4319 * overview.
4320 * @param remove If true, the tab at index will be removed after the
4321 * animation completes.
4322 */
4323 private void tabPicker(final boolean stay, final int index,
4324 final boolean remove) {
4325 if (mTabOverview != null) {
4326 return;
4327 }
4328
4329 int size = mTabControl.getTabCount();
4330
4331 TabListener l = null;
4332 if (stay) {
4333 l = mTabListener = new TabListener();
4334 }
4335 mTabOverview = new ImageGrid(this, stay, l);
4336
4337 for (int i = 0; i < size; i++) {
4338 final TabControl.Tab t = mTabControl.getTab(i);
4339 mTabControl.populatePickerData(t);
4340 mTabOverview.add(t);
4341 }
4342
4343 // Tell the tab overview to show the current tab, the tab overview will
4344 // handle the "New Tab" case.
4345 int currentIndex = mTabControl.getCurrentIndex();
4346 mTabOverview.setCurrentIndex(currentIndex);
4347
4348 // Attach the tab overview.
4349 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4350
4351 // Create a fake AnimatingView to animate the WebView's picture.
4352 final TabControl.Tab current = mTabControl.getCurrentTab();
4353 final AnimatingView v = new AnimatingView(this, current);
4354 mContentView.addView(v, COVER_SCREEN_PARAMS);
4355 removeTabFromContentView(current);
4356 // Pause timers to get the animation smoother.
4357 current.getWebView().pauseTimers();
4358
4359 // Send a message so the tab picker has a chance to layout and get
4360 // positions for all the cells.
4361 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4362 index, remove ? 1 : 0, v));
4363 // Setting this will indicate that we are animating to the overview. We
4364 // set it here to prevent another request to animate from coming in
4365 // between now and when ANIMATE_TO_OVERVIEW is handled.
4366 mAnimationCount++;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004367 // Always change the title bar to the window overview title while
4368 // animating.
4369 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4370 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4371 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4372 Window.PROGRESS_VISIBILITY_OFF);
4373 setTitle(R.string.tab_picker_title);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004374 // Make the menu empty until the animation completes.
4375 mMenuState = EMPTY_MENU;
4376 }
4377
4378 private void bookmarksPicker() {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004379 WebView current = mTabControl.getCurrentWebView();
4380 if (current == null) {
4381 return;
4382 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004383 Intent intent = new Intent(this,
4384 BrowserBookmarksPage.class);
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004385 String title = current.getTitle();
4386 String url = current.getUrl();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004387 // Just in case the user opens bookmarks before a page finishes loading
4388 // so the current history item, and therefore the page, is null.
4389 if (null == url) {
4390 url = mLastEnteredUrl;
4391 // This can happen.
4392 if (null == url) {
4393 url = mSettings.getHomePage();
4394 }
4395 }
4396 // In case the web page has not yet received its associated title.
4397 if (title == null) {
4398 title = url;
4399 }
4400 intent.putExtra("title", title);
4401 intent.putExtra("url", url);
4402 intent.putExtra("maxTabsOpen",
4403 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4404 startActivityForResult(intent, BOOKMARKS_PAGE);
4405 }
4406
The Android Open Source Projected217d92008-12-17 18:05:52 -08004407 // Called when loading from context menu or LOAD_URL message
4408 private void loadURL(WebView view, String url) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004409 // In case the user enters nothing.
The Android Open Source Projected217d92008-12-17 18:05:52 -08004410 if (url != null && url.length() != 0 && view != null) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004411 url = smartUrlFilter(url);
The Android Open Source Projected217d92008-12-17 18:05:52 -08004412 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4413 view.loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004414 }
4415 }
4416 }
4417
4418 private void checkMemory() {
4419 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4420 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4421 .getMemoryInfo(mi);
4422 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4423 // mi.threshold) for now
4424 // if (mi.lowMemory) {
4425 if (mi.availMem < mi.threshold) {
4426 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4427 + (mi.availMem / 1024) + "K threshold="
4428 + (mi.threshold / 1024) + "K");
4429 mTabControl.freeMemory();
4430 }
4431 }
4432
4433 private String smartUrlFilter(Uri inUri) {
4434 if (inUri != null) {
4435 return smartUrlFilter(inUri.toString());
4436 }
4437 return null;
4438 }
4439
4440
4441 // get window count
4442
4443 int getWindowCount(){
4444 if(mTabControl != null){
4445 return mTabControl.getTabCount();
4446 }
4447 return 0;
4448 }
4449
4450 static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4451 "(?i)" + // switch on case insensitive matching
4452 "(" + // begin group for schema
4453 "(?:http|https|file):\\/\\/" +
4454 "|(?:data|about|content|javascript):" +
4455 ")" +
4456 "(.*)" );
4457
4458 /**
4459 * Attempts to determine whether user input is a URL or search
4460 * terms. Anything with a space is passed to search.
4461 *
4462 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4463 * "Http://" converts to "http://"
4464 *
4465 * @return Original or modified URL
4466 *
4467 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08004468 String smartUrlFilter(String url) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004469
The Android Open Source Projected217d92008-12-17 18:05:52 -08004470 String inUrl = url.trim();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004471 boolean hasSpace = inUrl.indexOf(' ') != -1;
4472
The Android Open Source Projected217d92008-12-17 18:05:52 -08004473 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4474 if (matcher.matches()) {
4475 if (hasSpace) {
4476 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004477 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08004478 // force scheme to lowercase
4479 String scheme = matcher.group(1);
4480 String lcScheme = scheme.toLowerCase();
4481 if (!lcScheme.equals(scheme)) {
4482 return lcScheme + matcher.group(2);
4483 }
4484 return inUrl;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004485 }
4486 if (hasSpace) {
4487 // FIXME: quick search, need to be customized by setting
4488 if (inUrl.length() > 2 && inUrl.charAt(1) == ' ') {
4489 // FIXME: Is this the correct place to add to searches?
4490 // what if someone else calls this function?
4491 char char0 = inUrl.charAt(0);
4492
4493 if (char0 == 'g') {
4494 Browser.addSearchUrl(mResolver, inUrl);
4495 return composeSearchUrl(inUrl.substring(2));
4496
4497 } else if (char0 == 'w') {
4498 Browser.addSearchUrl(mResolver, inUrl);
4499 return URLUtil.composeSearchUrl(inUrl.substring(2),
4500 QuickSearch_W,
4501 QUERY_PLACE_HOLDER);
4502
4503 } else if (char0 == 'd') {
4504 Browser.addSearchUrl(mResolver, inUrl);
4505 return URLUtil.composeSearchUrl(inUrl.substring(2),
4506 QuickSearch_D,
4507 QUERY_PLACE_HOLDER);
4508
4509 } else if (char0 == 'l') {
4510 Browser.addSearchUrl(mResolver, inUrl);
4511 // FIXME: we need location in this case
4512 return URLUtil.composeSearchUrl(inUrl.substring(2),
4513 QuickSearch_L,
4514 QUERY_PLACE_HOLDER);
4515 }
4516 }
4517 } else {
4518 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4519 return URLUtil.guessUrl(inUrl);
4520 }
4521 }
4522
4523 Browser.addSearchUrl(mResolver, inUrl);
4524 return composeSearchUrl(inUrl);
4525 }
4526
4527 /* package */static String composeSearchUrl(String search) {
4528 return URLUtil.composeSearchUrl(search, QuickSearch_G,
4529 QUERY_PLACE_HOLDER);
4530 }
4531
The Android Open Source Projected217d92008-12-17 18:05:52 -08004532 /* package */void setBaseSearchUrl(String url) {
4533 if (url == null || url.length() == 0) {
4534 /*
4535 * get the google search url based on the SIM. Default is US. NOTE:
4536 * This code uses resources to optionally select the search Uri,
4537 * based on the MCC value from the SIM. The default string will most
4538 * likely be fine. It is parameterized to accept info from the
4539 * Locale, the language code is the first parameter (%1$s) and the
4540 * country code is the second (%2$s). This code must function in the
4541 * same way as a similar lookup in
4542 * com.android.googlesearch.SuggestionProvider#onCreate(). If you
4543 * change either of these functions, change them both. (The same is
4544 * true for the underlying resource strings, which are stored in
4545 * mcc-specific xml files.)
4546 */
4547 Locale l = Locale.getDefault();
4548 QuickSearch_G = getResources().getString(
4549 R.string.google_search_base, l.getLanguage(),
4550 l.getCountry().toLowerCase())
4551 + "client=ms-"
4552 + SystemProperties.get("ro.com.google.clientid", "unknown")
4553 + "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&q=%s";
4554 } else {
4555 QuickSearch_G = url;
4556 }
4557 }
4558
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004559 private final static int LOCK_ICON_UNSECURE = 0;
4560 private final static int LOCK_ICON_SECURE = 1;
4561 private final static int LOCK_ICON_MIXED = 2;
4562
4563 private int mLockIconType = LOCK_ICON_UNSECURE;
4564 private int mPrevLockType = LOCK_ICON_UNSECURE;
4565
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004566 private BrowserSettings mSettings;
4567 private TabControl mTabControl;
4568 private ContentResolver mResolver;
4569 private FrameLayout mContentView;
4570 private ImageGrid mTabOverview;
4571
4572 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4573 // view, we should rewrite this.
4574 private int mCurrentMenuState = 0;
4575 private int mMenuState = R.id.MAIN_MENU;
4576 private static final int EMPTY_MENU = -1;
4577 private Menu mMenu;
4578
4579 private FindDialog mFindDialog;
4580 // Used to prevent chording to result in firing two shortcuts immediately
4581 // one after another. Fixes bug 1211714.
4582 boolean mCanChord;
4583
4584 private boolean mInLoad;
4585
4586 private boolean mPageStarted;
4587 private boolean mActivityInPause = true;
4588
4589 private boolean mMenuIsDown;
4590
4591 private final KeyTracker mKeyTracker = new KeyTracker(this);
4592
4593 // As trackball doesn't send repeat down, we have to track it ourselves
4594 private boolean mTrackTrackball;
4595
4596 private static boolean mInTrace;
4597
4598 // Performance probe
4599 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4600 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4601 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4602 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4603 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4604 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4605 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4606 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4607 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4608 };
4609
4610 private long mStart;
4611 private long mProcessStart;
4612 private long mUserStart;
4613 private long mSystemStart;
4614 private long mIdleStart;
4615 private long mIrqStart;
4616
4617 private long mUiStart;
4618
4619 private Drawable mMixLockIcon;
4620 private Drawable mSecLockIcon;
4621 private Drawable mGenericFavicon;
4622
4623 /* hold a ref so we can auto-cancel if necessary */
4624 private AlertDialog mAlertDialog;
4625
4626 // Wait for credentials before loading google.com
4627 private ProgressDialog mCredsDlg;
4628
4629 // The up-to-date URL and title (these can be different from those stored
4630 // in WebView, since it takes some time for the information in WebView to
4631 // get updated)
4632 private String mUrl;
4633 private String mTitle;
4634
4635 // As PageInfo has different style for landscape / portrait, we have
4636 // to re-open it when configuration changed
4637 private AlertDialog mPageInfoDialog;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004638 private TabControl.Tab mPageInfoView;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004639 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4640 // dialog, we should not just dismiss it, but should get back to the
4641 // SSL-certificate-on-error dialog. This flag is used to store this state
4642 private Boolean mPageInfoFromShowSSLCertificateOnError;
4643
4644 // as SSLCertificateOnError has different style for landscape / portrait,
4645 // we have to re-open it when configuration changed
4646 private AlertDialog mSSLCertificateOnErrorDialog;
4647 private WebView mSSLCertificateOnErrorView;
4648 private SslErrorHandler mSSLCertificateOnErrorHandler;
4649 private SslError mSSLCertificateOnErrorError;
4650
4651 // as SSLCertificate has different style for landscape / portrait, we
4652 // have to re-open it when configuration changed
4653 private AlertDialog mSSLCertificateDialog;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004654 private TabControl.Tab mSSLCertificateView;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004655
4656 // as HttpAuthentication has different style for landscape / portrait, we
4657 // have to re-open it when configuration changed
4658 private AlertDialog mHttpAuthenticationDialog;
4659 private HttpAuthHandler mHttpAuthHandler;
4660
4661 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4662 new FrameLayout.LayoutParams(
4663 ViewGroup.LayoutParams.FILL_PARENT,
4664 ViewGroup.LayoutParams.FILL_PARENT);
4665 // We may provide UI to customize these
4666 // Google search from the browser
The Android Open Source Projected217d92008-12-17 18:05:52 -08004667 static String QuickSearch_G;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004668 // Wikipedia search
4669 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4670 // Dictionary search
4671 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4672 // Google Mobile Local search
4673 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4674
The Android Open Source Projected217d92008-12-17 18:05:52 -08004675 final static String QUERY_PLACE_HOLDER = "%s";
4676
4677 // "source" parameter for Google search through search key
4678 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4679 // "source" parameter for Google search through search menu
4680 final static String GOOGLE_SEARCH_SOURCE_SEARCHMENU = "browser-menu";
4681 // "source" parameter for Google search through goto menu
4682 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4683 // "source" parameter for Google search through simplily type
4684 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4685 // "source" parameter for Google search suggested by the browser
4686 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4687 // "source" parameter for Google search from unknown source
4688 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004689
4690 private final static String LOGTAG = "browser";
4691
4692 private TabListener mTabListener;
4693
4694 private String mLastEnteredUrl;
4695
4696 private PowerManager.WakeLock mWakeLock;
4697 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4698
4699 private Toast mStopToast;
4700
4701 // Used during animations to prevent other animations from being triggered.
4702 // A count is used since the animation to and from the Window overview can
4703 // overlap. A count of 0 means no animation where a count of > 0 means
4704 // there are animations in progress.
4705 private int mAnimationCount;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004706
4707 // As the ids are dynamically created, we can't guarantee that they will
4708 // be in sequence, so this static array maps ids to a window number.
4709 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4710 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4711 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4712 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004713
4714 // monitor platform changes
4715 private IntentFilter mNetworkStateChangedFilter;
4716 private BroadcastReceiver mNetworkStateIntentReceiver;
4717
4718 // activity requestCode
4719 final static int BOOKMARKS_PAGE = 1;
4720 final static int CLASSIC_HISTORY_PAGE = 2;
4721 final static int DOWNLOAD_PAGE = 3;
4722 final static int PREFERENCES_PAGE = 4;
4723
4724 // the frenquency of checking whether system memory is low
4725 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
4726}