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