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