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