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