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