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