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