blob: d8fd3fa524ecb98fec07065bf6ba6eae3e0855bd [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 Projectb7775e12009-02-10 15:44:04 -080057import android.net.ConnectivityManager;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -070058import android.net.Uri;
59import android.net.WebAddress;
60import android.net.http.EventHandler;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -070061import 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;
The Android Open Source Projectb7775e12009-02-10 15:44:04 -0800100import android.view.WindowManager;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700101import android.view.animation.AlphaAnimation;
102import android.view.animation.Animation;
103import android.view.animation.AnimationSet;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700104import android.view.animation.DecelerateInterpolator;
105import android.view.animation.ScaleAnimation;
106import android.view.animation.TranslateAnimation;
107import android.webkit.CookieManager;
108import android.webkit.CookieSyncManager;
109import android.webkit.DownloadListener;
110import android.webkit.HttpAuthHandler;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700111import android.webkit.SslErrorHandler;
112import android.webkit.URLUtil;
113import android.webkit.WebChromeClient;
114import android.webkit.WebHistoryItem;
115import android.webkit.WebIconDatabase;
116import android.webkit.WebView;
117import android.webkit.WebViewClient;
118import android.widget.EditText;
119import android.widget.FrameLayout;
120import android.widget.LinearLayout;
121import android.widget.TextView;
122import android.widget.Toast;
The Android Open Source Projectfbb2a3a2009-02-13 12:57:52 -0800123import android.widget.ZoomRingController;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700124
125import com.google.android.googleapps.IGoogleLoginService;
126import com.google.android.googlelogin.GoogleLoginServiceConstants;
127
128import java.io.BufferedOutputStream;
129import java.io.File;
130import java.io.FileInputStream;
131import java.io.FileOutputStream;
132import java.io.InputStream;
133import java.io.IOException;
134import java.net.MalformedURLException;
The Android Open Source Projectfbb2a3a2009-02-13 12:57:52 -0800135import java.net.URI;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700136import java.net.URL;
137import java.net.URLEncoder;
138import java.text.ParseException;
139import java.util.Date;
140import java.util.Enumeration;
141import java.util.HashMap;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700142import java.util.List;
The Android Open Source Projected217d92008-12-17 18:05:52 -0800143import java.util.Locale;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700144import java.util.regex.Matcher;
145import java.util.regex.Pattern;
146import java.util.Vector;
147import java.util.zip.ZipEntry;
148import java.util.zip.ZipFile;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700149
150public class BrowserActivity extends Activity
151 implements KeyTracker.OnKeyTracker,
152 View.OnCreateContextMenuListener,
153 DownloadListener {
154
155 private IGoogleLoginService mGls = null;
156 private ServiceConnection mGlsConnection = null;
157
158 private SensorManager mSensorManager = null;
159
160 /* Whitelisted webpages
161 private static HashSet<String> sWhiteList;
162
163 static {
164 sWhiteList = new HashSet<String>();
165 sWhiteList.add("cnn.com/");
166 sWhiteList.add("espn.go.com/");
167 sWhiteList.add("nytimes.com/");
168 sWhiteList.add("engadget.com/");
169 sWhiteList.add("yahoo.com/");
170 sWhiteList.add("msn.com/");
171 sWhiteList.add("amazon.com/");
172 sWhiteList.add("consumerist.com/");
173 sWhiteList.add("google.com/m/news");
174 }
175 */
176
177 private void setupHomePage() {
178 final Runnable getAccount = new Runnable() {
179 public void run() {
The Android Open Source Projected217d92008-12-17 18:05:52 -0800180 // Lower priority
181 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700182 // get the default home page
183 String homepage = mSettings.getHomePage();
184
185 try {
186 if (mGls == null) return;
187
188 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
189 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
190
191 // three cases:
192 //
193 // hostedUser == googleUser
194 // The device has only a google account
195 //
196 // hostedUser != googleUser
197 // The device has a hosted account and a google account
198 //
199 // hostedUser != null, googleUser == null
200 // The device has only a hosted account (so far)
201
202 // developers might have no accounts at all
203 if (hostedUser == null) return;
204
205 if (googleUser == null || !hostedUser.equals(googleUser)) {
206 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
The Android Open Source Project066e9082009-01-20 14:03:59 -0800207 homepage = "http://www.google.com/m/a/" + domain + "?client=ms-" +
208 SystemProperties.get("ro.com.google.clientid", "unknown");
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700209 }
210 } catch (RemoteException ignore) {
211 // Login service died; carry on
212 } catch (RuntimeException ignore) {
213 // Login service died; carry on
214 } finally {
215 finish(homepage);
216 }
217 }
218
219 private void finish(final String homepage) {
220 mHandler.post(new Runnable() {
221 public void run() {
222 mSettings.setHomePage(BrowserActivity.this, homepage);
223 resumeAfterCredentials();
224
225 // as this is running in a separate thread,
The Android Open Source Project066e9082009-01-20 14:03:59 -0800226 // BrowserActivity's onDestroy() may have been called,
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700227 // which also calls unbindService().
228 if (mGlsConnection != null) {
229 // we no longer need to keep GLS open
230 unbindService(mGlsConnection);
231 mGlsConnection = null;
232 }
233 } });
234 } };
235
236 final boolean[] done = { false };
237
238 // Open a connection to the Google Login Service. The first
239 // time the connection is established, set up the homepage depending on
240 // the account in a background thread.
241 mGlsConnection = new ServiceConnection() {
242 public void onServiceConnected(ComponentName className, IBinder service) {
243 mGls = IGoogleLoginService.Stub.asInterface(service);
244 if (done[0] == false) {
245 done[0] = true;
The Android Open Source Projected217d92008-12-17 18:05:52 -0800246 Thread account = new Thread(getAccount);
247 account.setName("GLSAccount");
248 account.start();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700249 }
250 }
251 public void onServiceDisconnected(ComponentName className) {
252 mGls = null;
253 }
254 };
255
256 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
257 mGlsConnection, Context.BIND_AUTO_CREATE);
258 }
259
260 /**
261 * This class is in charge of installing pre-packaged plugins
262 * from the Browser assets directory to the user's data partition.
263 * Plugins are loaded from the "plugins" directory in the assets;
264 * Anything that is in this directory will be copied over to the
265 * user data partition in app_plugins.
266 */
267 private class CopyPlugins implements Runnable {
268 final static String TAG = "PluginsInstaller";
269 final static String ZIP_FILTER = "assets/plugins/";
270 final static String APK_PATH = "/system/app/Browser.apk";
271 final static String PLUGIN_EXTENSION = ".so";
272 final static String TEMPORARY_EXTENSION = "_temp";
273 final static String BUILD_INFOS_FILE = "build.prop";
274 final static String SYSTEM_BUILD_INFOS_FILE = "/system/"
275 + BUILD_INFOS_FILE;
276 final int BUFSIZE = 4096;
277 boolean mDoOverwrite = false;
278 String pluginsPath;
279 Context mContext;
280 File pluginsDir;
281 AssetManager manager;
282
283 public CopyPlugins (boolean overwrite, Context context) {
284 mDoOverwrite = overwrite;
285 mContext = context;
286 }
287
288 /**
289 * Returned a filtered list of ZipEntry.
290 * We list all the files contained in the zip and
291 * only returns the ones starting with the ZIP_FILTER
292 * path.
293 *
294 * @param zip the zip file used.
295 */
296 public Vector<ZipEntry> pluginsFilesFromZip(ZipFile zip) {
297 Vector<ZipEntry> list = new Vector<ZipEntry>();
298 Enumeration entries = zip.entries();
299 while (entries.hasMoreElements()) {
300 ZipEntry entry = (ZipEntry) entries.nextElement();
301 if (entry.getName().startsWith(ZIP_FILTER)) {
302 list.add(entry);
303 }
304 }
305 return list;
306 }
307
308 /**
309 * Utility method to copy the content from an inputstream
310 * to a file output stream.
311 */
312 public void copyStreams(InputStream is, FileOutputStream fos) {
313 BufferedOutputStream os = null;
314 try {
315 byte data[] = new byte[BUFSIZE];
316 int count;
317 os = new BufferedOutputStream(fos, BUFSIZE);
318 while ((count = is.read(data, 0, BUFSIZE)) != -1) {
319 os.write(data, 0, count);
320 }
321 os.flush();
322 } catch (IOException e) {
323 Log.e(TAG, "Exception while copying: " + e);
324 } finally {
325 try {
326 if (os != null) {
327 os.close();
328 }
329 } catch (IOException e2) {
330 Log.e(TAG, "Exception while closing the stream: " + e2);
331 }
332 }
333 }
334
335 /**
336 * Returns a string containing the contents of a file
337 *
338 * @param file the target file
339 */
340 private String contentsOfFile(File file) {
341 String ret = null;
342 FileInputStream is = null;
343 try {
344 byte[] buffer = new byte[BUFSIZE];
345 int count;
346 is = new FileInputStream(file);
347 StringBuffer out = new StringBuffer();
348
349 while ((count = is.read(buffer, 0, BUFSIZE)) != -1) {
350 out.append(new String(buffer, 0, count));
351 }
352 ret = out.toString();
353 } catch (IOException e) {
354 Log.e(TAG, "Exception getting contents of file " + e);
355 } finally {
356 if (is != null) {
357 try {
358 is.close();
359 } catch (IOException e2) {
360 Log.e(TAG, "Exception while closing the file: " + e2);
361 }
362 }
363 }
364 return ret;
365 }
366
367 /**
368 * Utility method to initialize the user data plugins path.
369 */
370 public void initPluginsPath() {
371 BrowserSettings s = BrowserSettings.getInstance();
372 pluginsPath = s.getPluginsPath();
373 if (pluginsPath == null) {
374 s.loadFromDb(mContext);
375 pluginsPath = s.getPluginsPath();
376 }
377 if (Config.LOGV) {
378 Log.v(TAG, "Plugin path: " + pluginsPath);
379 }
380 }
381
382 /**
383 * Utility method to delete a file or a directory
384 *
385 * @param file the File to delete
386 */
387 public void deleteFile(File file) {
388 File[] files = file.listFiles();
389 if ((files != null) && files.length > 0) {
390 for (int i=0; i< files.length; i++) {
391 deleteFile(files[i]);
392 }
393 }
394 if (!file.delete()) {
395 Log.e(TAG, file.getPath() + " could not get deleted");
396 }
397 }
398
399 /**
400 * Clean the content of the plugins directory.
401 * We delete the directory, then recreate it.
402 */
403 public void cleanPluginsDirectory() {
404 if (Config.LOGV) {
405 Log.v(TAG, "delete plugins directory: " + pluginsPath);
406 }
407 File pluginsDirectory = new File(pluginsPath);
408 deleteFile(pluginsDirectory);
409 pluginsDirectory.mkdir();
410 }
411
412
413 /**
414 * Copy the SYSTEM_BUILD_INFOS_FILE file containing the
415 * informations about the system build to the
416 * BUILD_INFOS_FILE in the plugins directory.
417 */
418 public void copyBuildInfos() {
419 try {
420 if (Config.LOGV) {
421 Log.v(TAG, "Copy build infos to the plugins directory");
422 }
423 File buildInfoFile = new File(SYSTEM_BUILD_INFOS_FILE);
424 File buildInfoPlugins = new File(pluginsPath, BUILD_INFOS_FILE);
425 copyStreams(new FileInputStream(buildInfoFile),
426 new FileOutputStream(buildInfoPlugins));
427 } catch (IOException e) {
428 Log.e(TAG, "Exception while copying the build infos: " + e);
429 }
430 }
431
432 /**
433 * Returns true if the current system is newer than the
434 * system that installed the plugins.
435 * We determinate this by checking the build number of the system.
436 *
437 * At the end of the plugins copy operation, we copy the
438 * SYSTEM_BUILD_INFOS_FILE to the BUILD_INFOS_FILE.
439 * We then just have to load both and compare them -- if they
440 * are different the current system is newer.
441 *
442 * Loading and comparing the strings should be faster than
443 * creating a hash, the files being rather small. Extracting the
444 * version number would require some parsing which may be more
445 * brittle.
446 */
447 public boolean newSystemImage() {
448 try {
449 File buildInfoFile = new File(SYSTEM_BUILD_INFOS_FILE);
450 File buildInfoPlugins = new File(pluginsPath, BUILD_INFOS_FILE);
451 if (!buildInfoPlugins.exists()) {
452 if (Config.LOGV) {
453 Log.v(TAG, "build.prop in plugins directory " + pluginsPath
454 + " does not exist, therefore it's a new system image");
455 }
456 return true;
457 } else {
458 String buildInfo = contentsOfFile(buildInfoFile);
459 String buildInfoPlugin = contentsOfFile(buildInfoPlugins);
460 if (buildInfo == null || buildInfoPlugin == null
461 || buildInfo.compareTo(buildInfoPlugin) != 0) {
462 if (Config.LOGV) {
463 Log.v(TAG, "build.prop are different, "
464 + " therefore it's a new system image");
465 }
466 return true;
467 }
468 }
469 } catch (Exception e) {
470 Log.e(TAG, "Exc in newSystemImage(): " + e);
471 }
472 return false;
473 }
474
475 /**
476 * Check if the version of the plugins contained in the
477 * Browser assets is the same as the version of the plugins
478 * in the plugins directory.
479 * We simply iterate on every file in the assets/plugins
480 * and return false if a file listed in the assets does
481 * not exist in the plugins directory.
482 */
483 private boolean checkIsDifferentVersions() {
484 try {
485 ZipFile zip = new ZipFile(APK_PATH);
486 Vector<ZipEntry> files = pluginsFilesFromZip(zip);
487 int zipFilterLength = ZIP_FILTER.length();
488
489 Enumeration entries = files.elements();
490 while (entries.hasMoreElements()) {
491 ZipEntry entry = (ZipEntry) entries.nextElement();
492 String path = entry.getName().substring(zipFilterLength);
493 File outputFile = new File(pluginsPath, path);
494 if (!outputFile.exists()) {
495 if (Config.LOGV) {
496 Log.v(TAG, "checkIsDifferentVersions(): extracted file "
497 + path + " does not exist, we have a different version");
498 }
499 return true;
500 }
501 }
502 } catch (IOException e) {
503 Log.e(TAG, "Exception in checkDifferentVersions(): " + e);
504 }
505 return false;
506 }
507
508 /**
509 * Copy every files from the assets/plugins directory
510 * to the app_plugins directory in the data partition.
511 * Once copied, we copy over the SYSTEM_BUILD_INFOS file
512 * in the plugins directory.
513 *
514 * NOTE: we directly access the content from the Browser
515 * package (it's a zip file) and do not use AssetManager
516 * as there is a limit of 1Mb (see Asset.h)
517 */
518 public void run() {
The Android Open Source Projected217d92008-12-17 18:05:52 -0800519 // Lower the priority
520 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700521 try {
522 if (pluginsPath == null) {
523 Log.e(TAG, "No plugins path found!");
524 return;
525 }
526
527 ZipFile zip = new ZipFile(APK_PATH);
528 Vector<ZipEntry> files = pluginsFilesFromZip(zip);
529 Vector<File> plugins = new Vector<File>();
530 int zipFilterLength = ZIP_FILTER.length();
531
532 Enumeration entries = files.elements();
533 while (entries.hasMoreElements()) {
534 ZipEntry entry = (ZipEntry) entries.nextElement();
535 String path = entry.getName().substring(zipFilterLength);
536 File outputFile = new File(pluginsPath, path);
537 outputFile.getParentFile().mkdirs();
538
539 if (outputFile.exists() && !mDoOverwrite) {
540 if (Config.LOGV) {
541 Log.v(TAG, path + " already extracted.");
542 }
543 } else {
544 if (path.endsWith(PLUGIN_EXTENSION)) {
545 // We rename plugins to be sure a half-copied
546 // plugin is not loaded by the browser.
547 plugins.add(outputFile);
548 outputFile = new File(pluginsPath,
549 path + TEMPORARY_EXTENSION);
550 }
551 FileOutputStream fos = new FileOutputStream(outputFile);
552 if (Config.LOGV) {
553 Log.v(TAG, "copy " + entry + " to "
554 + pluginsPath + "/" + path);
555 }
556 copyStreams(zip.getInputStream(entry), fos);
557 }
558 }
559
560 // We now rename the .so we copied, once all their resources
561 // are safely copied over to the user data partition.
562 Enumeration elems = plugins.elements();
563 while (elems.hasMoreElements()) {
564 File renamedFile = (File) elems.nextElement();
565 File sourceFile = new File(renamedFile.getPath()
566 + TEMPORARY_EXTENSION);
567 if (Config.LOGV) {
568 Log.v(TAG, "rename " + sourceFile.getPath()
569 + " to " + renamedFile.getPath());
570 }
571 sourceFile.renameTo(renamedFile);
572 }
573
574 copyBuildInfos();
575
576 // Refresh the plugin list.
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800577 if (mTabControl.getCurrentWebView() != null) {
578 mTabControl.getCurrentWebView().refreshPlugins(false);
579 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700580 } catch (IOException e) {
581 Log.e(TAG, "IO Exception: " + e);
582 }
583 }
584 };
585
586 /**
587 * Copy the content of assets/plugins/ to the app_plugins directory
588 * in the data partition.
589 *
590 * This function is called every time the browser is started.
591 * We first check if the system image is newer than the one that
592 * copied the plugins (if there's plugins in the data partition).
593 * If this is the case, we then check if the versions are different.
594 * If they are different, we clean the plugins directory in the
595 * data partition, then start a thread to copy the plugins while
596 * the browser continue to load.
597 *
598 * @param overwrite if true overwrite the files even if they are
599 * already present (to let the user "reset" the plugins if needed).
600 */
601 private void copyPlugins(boolean overwrite) {
602 CopyPlugins copyPluginsFromAssets = new CopyPlugins(overwrite, this);
603 copyPluginsFromAssets.initPluginsPath();
604 if (copyPluginsFromAssets.newSystemImage()) {
605 if (copyPluginsFromAssets.checkIsDifferentVersions()) {
606 copyPluginsFromAssets.cleanPluginsDirectory();
The Android Open Source Projected217d92008-12-17 18:05:52 -0800607 Thread copyplugins = new Thread(copyPluginsFromAssets);
608 copyplugins.setName("CopyPlugins");
609 copyplugins.start();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700610 }
611 }
612 }
613
The Android Open Source Projected217d92008-12-17 18:05:52 -0800614 private class ClearThumbnails extends AsyncTask<File, Void, Void> {
615 @Override
616 public Void doInBackground(File... files) {
617 if (files != null) {
618 for (File f : files) {
619 f.delete();
620 }
621 }
622 return null;
623 }
624 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700625
626 @Override public void onCreate(Bundle icicle) {
627 if (Config.LOGV) {
628 Log.v(LOGTAG, this + " onStart");
629 }
630 super.onCreate(icicle);
631 this.requestWindowFeature(Window.FEATURE_LEFT_ICON);
632 this.requestWindowFeature(Window.FEATURE_RIGHT_ICON);
633 this.requestWindowFeature(Window.FEATURE_PROGRESS);
634 this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
635
636 // test the browser in OpenGL
637 // requestWindowFeature(Window.FEATURE_OPENGL);
638
639 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
640
641 mResolver = getContentResolver();
642
The Android Open Source Projected217d92008-12-17 18:05:52 -0800643 setBaseSearchUrl(PreferenceManager.getDefaultSharedPreferences(this)
644 .getString("search_url", ""));
645
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700646 //
647 // start MASF proxy service
648 //
649 //Intent proxyServiceIntent = new Intent();
650 //proxyServiceIntent.setComponent
651 // (new ComponentName(
652 // "com.android.masfproxyservice",
653 // "com.android.masfproxyservice.MasfProxyService"));
654 //startService(proxyServiceIntent, null);
655
656 mSecLockIcon = Resources.getSystem().getDrawable(
657 android.R.drawable.ic_secure);
658 mMixLockIcon = Resources.getSystem().getDrawable(
659 android.R.drawable.ic_partial_secure);
660 mGenericFavicon = getResources().getDrawable(
661 R.drawable.app_web_browser_sm);
662
The Android Open Source Project066e9082009-01-20 14:03:59 -0800663 mContentView = (FrameLayout) getWindow().getDecorView().findViewById(
664 com.android.internal.R.id.content);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700665
666 // Create the tab control and our initial tab
667 mTabControl = new TabControl(this);
668
669 // Open the icon database and retain all the bookmark urls for favicons
670 retainIconsOnStartup();
671
672 // Keep a settings instance handy.
673 mSettings = BrowserSettings.getInstance();
674 mSettings.setTabControl(mTabControl);
675 mSettings.loadFromDb(this);
676
677 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
678 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
679
680 if (!mTabControl.restoreState(icicle)) {
The Android Open Source Projected217d92008-12-17 18:05:52 -0800681 // clear up the thumbnail directory if we can't restore the state as
682 // none of the files in the directory are referenced any more.
683 new ClearThumbnails().execute(
684 mTabControl.getThumbnailDir().listFiles());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700685 final Intent intent = getIntent();
686 final Bundle extra = intent.getExtras();
687 // Create an initial tab.
The Android Open Source Projected217d92008-12-17 18:05:52 -0800688 // If the intent is ACTION_VIEW and data is not null, the Browser is
689 // invoked to view the content by another application. In this case,
690 // the tab will be close when exit.
691 final TabControl.Tab t = mTabControl.createNewTab(
692 Intent.ACTION_VIEW.equals(intent.getAction()) &&
693 intent.getData() != null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700694 mTabControl.setCurrentTab(t);
695 // This is one of the only places we call attachTabToContentView
696 // without animating from the tab picker.
697 attachTabToContentView(t);
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800698 WebView webView = t.getWebView();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700699 if (extra != null) {
700 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
701 if (scale > 0 && scale <= 1000) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800702 webView.setInitialScale(scale);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700703 }
704 }
705 // If we are not restoring from an icicle, then there is a high
706 // likely hood this is the first run. So, check to see if the
707 // homepage needs to be configured and copy any plugins from our
708 // asset directory to the data partition.
709 if ((extra == null || !extra.getBoolean("testing"))
710 && !mSettings.isLoginInitialized()) {
711 setupHomePage();
712 }
713 copyPlugins(true);
714
715 String url = getUrlFromIntent(intent);
716 if (url == null || url.length() == 0) {
717 if (mSettings.isLoginInitialized()) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800718 webView.loadUrl(mSettings.getHomePage());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700719 } else {
720 waitForCredentials();
721 }
722 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800723 webView.loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700724 }
725 } else {
726 // TabControl.restoreState() will create a new tab even if
727 // restoring the state fails. Attach it to the view here since we
728 // are not animating from the tab picker.
729 attachTabToContentView(mTabControl.getCurrentTab());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700730 }
731
732 /* enables registration for changes in network status from
733 http stack */
734 mNetworkStateChangedFilter = new IntentFilter();
735 mNetworkStateChangedFilter.addAction(
The Android Open Source Projectb7775e12009-02-10 15:44:04 -0800736 ConnectivityManager.CONNECTIVITY_ACTION);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700737 mNetworkStateIntentReceiver = new BroadcastReceiver() {
738 @Override
739 public void onReceive(Context context, Intent intent) {
740 if (intent.getAction().equals(
The Android Open Source Projectb7775e12009-02-10 15:44:04 -0800741 ConnectivityManager.CONNECTIVITY_ACTION)) {
742 boolean down = intent.getBooleanExtra(
743 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
744 onNetworkToggle(!down);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700745 }
746 }
747 };
The Android Open Source Projectfbb2a3a2009-02-13 12:57:52 -0800748
749 // Show a tutorial for the new zoom interaction (the method ensure we only show it once)
750 ZoomRingController.showZoomTutorialOnce(this);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700751 }
752
753 @Override
754 protected void onNewIntent(Intent intent) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800755 TabControl.Tab current = mTabControl.getCurrentTab();
The Android Open Source Projected217d92008-12-17 18:05:52 -0800756 // When a tab is closed on exit, the current tab index is set to -1.
757 // Reset before proceed as Browser requires the current tab to be set.
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800758 if (current == null) {
759 // Try to reset the tab in case the index was incorrect.
760 current = mTabControl.getTab(0);
761 if (current == null) {
762 // No tabs at all so just ignore this intent.
763 return;
764 }
The Android Open Source Projected217d92008-12-17 18:05:52 -0800765 mTabControl.setCurrentTab(current);
766 attachTabToContentView(current);
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800767 resetTitleAndIcon(current.getWebView());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700768 }
769 final String action = intent.getAction();
770 final int flags = intent.getFlags();
The Android Open Source Project066e9082009-01-20 14:03:59 -0800771 if (Intent.ACTION_MAIN.equals(action) ||
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700772 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
773 // just resume the browser
774 return;
775 }
776 if (Intent.ACTION_VIEW.equals(action)
777 || Intent.ACTION_SEARCH.equals(action)
The Android Open Source Projected217d92008-12-17 18:05:52 -0800778 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700779 || Intent.ACTION_WEB_SEARCH.equals(action)) {
780 String url = getUrlFromIntent(intent);
781 if (url == null || url.length() == 0) {
782 url = mSettings.getHomePage();
783 }
The Android Open Source Project066e9082009-01-20 14:03:59 -0800784 if (Intent.ACTION_VIEW.equals(action) &&
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700785 (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
786 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url will be
The Android Open Source Projected217d92008-12-17 18:05:52 -0800787 // opened in a new tab unless we have reached MAX_TABS. Then the
788 // url will be opened in the current tab. If a new tab is
789 // created, it will have "true" for exit on close.
790 openTabAndShow(url, null, true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700791 } else {
792 if ("about:debug".equals(url)) {
793 mSettings.toggleDebugSettings();
794 return;
795 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700796 // If the Window overview is up and we are not in the midst of
797 // an animation, animate away from the Window overview.
798 if (mTabOverview != null && mAnimationCount == 0) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800799 sendAnimateFromOverview(current, false, url,
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700800 TAB_OVERVIEW_DELAY, null);
801 } else {
802 // Get rid of the subwindow if it exists
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800803 dismissSubWindow(current);
804 current.getWebView().loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700805 }
806 }
807 }
808 }
809
810 private String getUrlFromIntent(Intent intent) {
811 String url = null;
812 if (intent != null) {
813 final String action = intent.getAction();
814 if (Intent.ACTION_VIEW.equals(action)) {
815 url = smartUrlFilter(intent.getData());
816 if (url != null && url.startsWith("content:")) {
817 /* Append mimetype so webview knows how to display */
818 String mimeType = intent.resolveType(getContentResolver());
819 if (mimeType != null) {
820 url += "?" + mimeType;
821 }
822 }
823 } else if (Intent.ACTION_SEARCH.equals(action)
The Android Open Source Projected217d92008-12-17 18:05:52 -0800824 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700825 || Intent.ACTION_WEB_SEARCH.equals(action)) {
826 url = intent.getStringExtra(SearchManager.QUERY);
The Android Open Source Projected217d92008-12-17 18:05:52 -0800827 if (url != null) {
828 mLastEnteredUrl = url;
829 // Don't add Urls, just search terms.
830 // Urls will get added when the page is loaded.
831 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
832 Browser.updateVisitedHistory(mResolver, url, false);
833 }
834 // In general, we shouldn't modify URL from Intent.
835 // But currently, we get the user-typed URL from search box as well.
836 url = fixUrl(url);
837 url = smartUrlFilter(url);
838 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
839 if (url.contains(searchSource)) {
840 String source = null;
841 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
842 if (appData != null) {
843 source = appData.getString(SearchManager.SOURCE);
844 }
845 if (TextUtils.isEmpty(source)) {
846 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
847 }
848 url = url.replace(searchSource, "&source=android-"+source+"&");
849 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700850 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700851 }
852 }
853 return url;
854 }
855
The Android Open Source Projected217d92008-12-17 18:05:52 -0800856 /* package */ static String fixUrl(String inUrl) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700857 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
858 return inUrl;
859 if (inUrl.startsWith("http:") ||
860 inUrl.startsWith("https:")) {
861 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
862 inUrl = inUrl.replaceFirst("/", "//");
863 } else inUrl = inUrl.replaceFirst(":", "://");
864 }
865 return inUrl;
866 }
867
868 /**
869 * Looking for the pattern like this
The Android Open Source Project066e9082009-01-20 14:03:59 -0800870 *
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700871 * *
872 * * *
873 * *** * *******
874 * * *
875 * * *
876 * *
877 */
878 private final SensorListener mSensorListener = new SensorListener() {
879 private long mLastGestureTime;
880 private float[] mPrev = new float[3];
881 private float[] mPrevDiff = new float[3];
882 private float[] mDiff = new float[3];
883 private float[] mRevertDiff = new float[3];
884
885 public void onSensorChanged(int sensor, float[] values) {
886 boolean show = false;
887 float[] diff = new float[3];
The Android Open Source Project066e9082009-01-20 14:03:59 -0800888
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700889 for (int i = 0; i < 3; i++) {
890 diff[i] = values[i] - mPrev[i];
891 if (Math.abs(diff[i]) > 1) {
892 show = true;
893 }
894 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
895 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
896 // start track when there is a big move, or revert
897 mRevertDiff[i] = mDiff[i];
898 mDiff[i] = 0;
899 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
900 // reset when it is flat
901 mDiff[i] = mRevertDiff[i] = 0;
902 }
903 mDiff[i] += diff[i];
904 mPrevDiff[i] = diff[i];
905 mPrev[i] = values[i];
906 }
907
908 if (false) {
909 // only shows if we think the delta is big enough, in an attempt
910 // to detect "serious" moves left/right or up/down
911 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
912 + values[0] + ", " + values[1] + ", " + values[2] + ")"
913 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
914 + ")");
915 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
916 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
917 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
918 + mRevertDiff[2] + ")");
919 }
920
921 long now = android.os.SystemClock.uptimeMillis();
922 if (now - mLastGestureTime > 1000) {
923 mLastGestureTime = 0;
924
925 float y = mDiff[1];
926 float z = mDiff[2];
927 float ay = Math.abs(y);
928 float az = Math.abs(z);
929 float ry = mRevertDiff[1];
930 float rz = mRevertDiff[2];
931 float ary = Math.abs(ry);
932 float arz = Math.abs(rz);
933 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
934 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
935
936 if ((gestY || gestZ) && !(gestY && gestZ)) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800937 WebView view = mTabControl.getCurrentWebView();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700938
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800939 if (view != null) {
940 if (gestZ) {
941 if (z < 0) {
942 view.zoomOut();
943 } else {
944 view.zoomIn();
945 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700946 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -0800947 view.flingScroll(0, Math.round(y * 100));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700948 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700949 }
950 mLastGestureTime = now;
951 }
952 }
953 }
954
955 public void onAccuracyChanged(int sensor, int accuracy) {
956 // TODO Auto-generated method stub
The Android Open Source Project066e9082009-01-20 14:03:59 -0800957
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -0700958 }
959 };
960
961 @Override protected void onResume() {
962 super.onResume();
963 if (Config.LOGV) {
964 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
965 }
966
967 if (!mActivityInPause) {
968 Log.e(LOGTAG, "BrowserActivity is already resumed.");
969 return;
970 }
971
972 mActivityInPause = false;
973 resumeWebView();
974
975 if (mWakeLock.isHeld()) {
976 mHandler.removeMessages(RELEASE_WAKELOCK);
977 mWakeLock.release();
978 }
979
980 if (mCredsDlg != null) {
981 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
982 // In case credential request never comes back
983 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
984 }
985 }
986
987 registerReceiver(mNetworkStateIntentReceiver,
988 mNetworkStateChangedFilter);
989 WebView.enablePlatformNotifications();
990
991 if (mSettings.doFlick()) {
992 if (mSensorManager == null) {
993 mSensorManager = (SensorManager) getSystemService(
994 Context.SENSOR_SERVICE);
995 }
996 mSensorManager.registerListener(mSensorListener,
997 SensorManager.SENSOR_ACCELEROMETER,
998 SensorManager.SENSOR_DELAY_FASTEST);
999 } else {
1000 mSensorManager = null;
1001 }
1002 }
1003
1004 /**
1005 * onSaveInstanceState(Bundle map)
1006 * onSaveInstanceState is called right before onStop(). The map contains
1007 * the saved state.
1008 */
1009 @Override protected void onSaveInstanceState(Bundle outState) {
1010 if (Config.LOGV) {
1011 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1012 }
1013 // the default implementation requires each view to have an id. As the
1014 // browser handles the state itself and it doesn't use id for the views,
1015 // don't call the default implementation. Otherwise it will trigger the
The Android Open Source Project066e9082009-01-20 14:03:59 -08001016 // warning like this, "couldn't save which view has focus because the
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001017 // focused view XXX has no id".
1018
1019 // Save all the tabs
1020 mTabControl.saveState(outState);
1021 }
1022
1023 @Override protected void onPause() {
1024 super.onPause();
1025
1026 if (mActivityInPause) {
1027 Log.e(LOGTAG, "BrowserActivity is already paused.");
1028 return;
1029 }
1030
1031 mActivityInPause = true;
The Android Open Source Projected217d92008-12-17 18:05:52 -08001032 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebView()) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001033 mWakeLock.acquire();
1034 mHandler.sendMessageDelayed(mHandler
1035 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1036 }
1037
1038 // Clear the credentials toast if it is up
1039 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1040 mCredsDlg.dismiss();
1041 }
1042 mCredsDlg = null;
1043
1044 cancelStopToast();
1045
1046 // unregister network state listener
1047 unregisterReceiver(mNetworkStateIntentReceiver);
1048 WebView.disablePlatformNotifications();
1049
1050 if (mSensorManager != null) {
1051 mSensorManager.unregisterListener(mSensorListener);
1052 }
1053 }
1054
1055 @Override protected void onDestroy() {
1056 if (Config.LOGV) {
1057 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1058 }
1059 super.onDestroy();
1060 // Remove the current tab and sub window
1061 TabControl.Tab t = mTabControl.getCurrentTab();
1062 dismissSubWindow(t);
1063 removeTabFromContentView(t);
1064 // Destroy all the tabs
1065 mTabControl.destroy();
1066 WebIconDatabase.getInstance().close();
1067 if (mGlsConnection != null) {
1068 unbindService(mGlsConnection);
1069 mGlsConnection = null;
1070 }
1071
1072 //
1073 // stop MASF proxy service
1074 //
1075 //Intent proxyServiceIntent = new Intent();
1076 //proxyServiceIntent.setComponent
1077 // (new ComponentName(
1078 // "com.android.masfproxyservice",
1079 // "com.android.masfproxyservice.MasfProxyService"));
1080 //stopService(proxyServiceIntent);
1081 }
1082
1083 @Override
1084 public void onConfigurationChanged(Configuration newConfig) {
1085 super.onConfigurationChanged(newConfig);
The Android Open Source Project066e9082009-01-20 14:03:59 -08001086
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001087 if (mPageInfoDialog != null) {
1088 mPageInfoDialog.dismiss();
1089 showPageInfo(
1090 mPageInfoView,
1091 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1092 }
1093 if (mSSLCertificateDialog != null) {
1094 mSSLCertificateDialog.dismiss();
1095 showSSLCertificate(
1096 mSSLCertificateView);
1097 }
1098 if (mSSLCertificateOnErrorDialog != null) {
1099 mSSLCertificateOnErrorDialog.dismiss();
1100 showSSLCertificateOnError(
1101 mSSLCertificateOnErrorView,
1102 mSSLCertificateOnErrorHandler,
1103 mSSLCertificateOnErrorError);
1104 }
1105 if (mHttpAuthenticationDialog != null) {
1106 String title = ((TextView) mHttpAuthenticationDialog
1107 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1108 .toString();
1109 String name = ((TextView) mHttpAuthenticationDialog
1110 .findViewById(R.id.username_edit)).getText().toString();
1111 String password = ((TextView) mHttpAuthenticationDialog
1112 .findViewById(R.id.password_edit)).getText().toString();
1113 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1114 .getId();
1115 mHttpAuthenticationDialog.dismiss();
1116 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1117 name, password, focusId);
1118 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08001119 if (mFindDialog != null && mFindDialog.isShowing()) {
1120 mFindDialog.onConfigurationChanged(newConfig);
1121 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001122 }
1123
1124 @Override public void onLowMemory() {
1125 super.onLowMemory();
1126 mTabControl.freeMemory();
1127 }
1128
1129 private boolean resumeWebView() {
The Android Open Source Project066e9082009-01-20 14:03:59 -08001130 if ((!mActivityInPause && !mPageStarted) ||
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001131 (mActivityInPause && mPageStarted)) {
1132 CookieSyncManager.getInstance().startSync();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001133 WebView w = mTabControl.getCurrentWebView();
1134 if (w != null) {
1135 w.resumeTimers();
1136 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001137 return true;
1138 } else {
1139 return false;
1140 }
1141 }
1142
1143 private boolean pauseWebView() {
1144 if (mActivityInPause && !mPageStarted) {
1145 CookieSyncManager.getInstance().stopSync();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001146 WebView w = mTabControl.getCurrentWebView();
1147 if (w != null) {
1148 w.pauseTimers();
1149 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001150 return true;
1151 } else {
1152 return false;
1153 }
1154 }
1155
1156 /*
1157 * This function is called when we are launching for the first time. We
1158 * are waiting for the login credentials before loading Google home
1159 * pages. This way the user will be logged in straight away.
1160 */
1161 private void waitForCredentials() {
1162 // Show a toast
1163 mCredsDlg = new ProgressDialog(this);
1164 mCredsDlg.setIndeterminate(true);
1165 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
The Android Open Source Project066e9082009-01-20 14:03:59 -08001166 // If the user cancels the operation, then cancel the Google
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001167 // Credentials request.
1168 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1169 mCredsDlg.show();
1170
1171 // We set a timeout for the retrieval of credentials in onResume()
1172 // as that is when we have freed up some CPU time to get
1173 // the login credentials.
1174 }
1175
1176 /*
1177 * If we have received the credentials or we have timed out and we are
1178 * showing the credentials dialog, then it is time to move on.
1179 */
1180 private void resumeAfterCredentials() {
1181 if (mCredsDlg == null) {
1182 return;
1183 }
1184
1185 // Clear the toast
1186 if (mCredsDlg.isShowing()) {
1187 mCredsDlg.dismiss();
1188 }
1189 mCredsDlg = null;
1190
1191 // Clear any pending timeout
1192 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1193
1194 // Load the page
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001195 WebView w = mTabControl.getCurrentWebView();
1196 if (w != null) {
1197 w.loadUrl(mSettings.getHomePage());
1198 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001199
1200 // Update the settings, need to do this last as it can take a moment
1201 // to persist the settings. In the mean time we could be loading
1202 // content.
1203 mSettings.setLoginInitialized(this);
1204 }
1205
1206 // Open the icon database and retain all the icons for visited sites.
1207 private void retainIconsOnStartup() {
1208 final WebIconDatabase db = WebIconDatabase.getInstance();
1209 db.open(getDir("icons", 0).getPath());
1210 try {
1211 Cursor c = Browser.getAllBookmarks(mResolver);
1212 if (!c.moveToFirst()) {
1213 c.deactivate();
1214 return;
1215 }
1216 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1217 do {
1218 String url = c.getString(urlIndex);
1219 db.retainIconForPageUrl(url);
1220 } while (c.moveToNext());
1221 c.deactivate();
1222 } catch (IllegalStateException e) {
1223 Log.e(LOGTAG, "retainIconsOnStartup", e);
1224 }
1225 }
1226
1227 // Helper method for getting the top window.
1228 WebView getTopWindow() {
1229 return mTabControl.getCurrentTopWebView();
1230 }
1231
1232 @Override
1233 public boolean onCreateOptionsMenu(Menu menu) {
1234 super.onCreateOptionsMenu(menu);
1235
1236 MenuInflater inflater = getMenuInflater();
1237 inflater.inflate(R.menu.browser, menu);
1238 mMenu = menu;
1239 updateInLoadMenuItems();
1240 return true;
1241 }
1242
1243 /**
1244 * As the menu can be open when loading state changes
1245 * we must manually update the state of the stop/reload menu
1246 * item
1247 */
1248 private void updateInLoadMenuItems() {
1249 if (mMenu == null) {
1250 return;
1251 }
1252 MenuItem src = mInLoad ?
1253 mMenu.findItem(R.id.stop_menu_id):
1254 mMenu.findItem(R.id.reload_menu_id);
1255 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1256 dest.setIcon(src.getIcon());
1257 dest.setTitle(src.getTitle());
1258 }
1259
1260 @Override
1261 public boolean onContextItemSelected(MenuItem item) {
1262 // chording is not an issue with context menus, but we use the same
1263 // options selector, so set mCanChord to true so we can access them.
1264 mCanChord = true;
1265 int id = item.getItemId();
The Android Open Source Projected217d92008-12-17 18:05:52 -08001266 final WebView webView = getTopWindow();
1267 final HashMap hrefMap = new HashMap();
1268 hrefMap.put("webview", webView);
1269 final Message msg = mHandler.obtainMessage(
1270 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001271 switch (id) {
1272 // -- Browser context menu
1273 case R.id.open_context_menu_id:
1274 case R.id.open_newtab_context_menu_id:
1275 case R.id.bookmark_context_menu_id:
1276 case R.id.save_link_context_menu_id:
1277 case R.id.share_link_context_menu_id:
1278 case R.id.copy_link_context_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001279 webView.requestFocusNodeHref(msg);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001280 break;
1281
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001282 default:
1283 // For other context menus
1284 return onOptionsItemSelected(item);
1285 }
1286 mCanChord = false;
1287 return true;
1288 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08001289
1290 private Bundle createGoogleSearchSourceBundle(String source) {
1291 Bundle bundle = new Bundle();
1292 bundle.putString(SearchManager.SOURCE, source);
1293 return bundle;
1294 }
1295
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001296 /**
1297 * Overriding this forces the search key to launch global search. The difference
1298 * is the final "true" which requests global search.
1299 */
1300 @Override
1301 public boolean onSearchRequested() {
The Android Open Source Projected217d92008-12-17 18:05:52 -08001302 startSearch(null, false,
1303 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001304 return true;
1305 }
1306
1307 @Override
The Android Open Source Project066e9082009-01-20 14:03:59 -08001308 public void startSearch(String initialQuery, boolean selectInitialQuery,
The Android Open Source Projected217d92008-12-17 18:05:52 -08001309 Bundle appSearchData, boolean globalSearch) {
1310 if (appSearchData == null) {
1311 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1312 }
1313 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1314 }
1315
1316 @Override
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001317 public boolean onOptionsItemSelected(MenuItem item) {
1318 if (!mCanChord) {
1319 // The user has already fired a shortcut with this hold down of the
1320 // menu key.
1321 return false;
1322 }
1323 switch (item.getItemId()) {
1324 // -- Main menu
1325 case R.id.goto_menu_id: {
1326 String url = getTopWindow().getUrl();
The Android Open Source Projected217d92008-12-17 18:05:52 -08001327 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1328 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_GOTO), false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001329 }
1330 break;
The Android Open Source Projected217d92008-12-17 18:05:52 -08001331
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001332 case R.id.bookmarks_menu_id:
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08001333 bookmarksOrHistoryPicker(false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001334 break;
1335
1336 case R.id.windows_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001337 if (mTabControl.getTabCount() == 1) {
1338 openTabAndShow(mSettings.getHomePage(), null, false);
1339 } else {
1340 tabPicker(true, mTabControl.getCurrentIndex(), false);
1341 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001342 break;
1343
1344 case R.id.stop_reload_menu_id:
1345 if (mInLoad) {
1346 stopLoading();
1347 } else {
1348 getTopWindow().reload();
1349 }
1350 break;
1351
1352 case R.id.back_menu_id:
1353 getTopWindow().goBack();
1354 break;
1355
1356 case R.id.forward_menu_id:
1357 getTopWindow().goForward();
1358 break;
1359
1360 case R.id.close_menu_id:
1361 // Close the subwindow if it exists.
1362 if (mTabControl.getCurrentSubWindow() != null) {
1363 dismissSubWindow(mTabControl.getCurrentTab());
1364 break;
1365 }
1366 final int currentIndex = mTabControl.getCurrentIndex();
1367 final TabControl.Tab parent =
1368 mTabControl.getCurrentTab().getParentTab();
1369 int indexToShow = -1;
1370 if (parent != null) {
1371 indexToShow = mTabControl.getTabIndex(parent);
1372 } else {
1373 // Get the last tab in the list. If it is the current tab,
1374 // subtract 1 more.
1375 indexToShow = mTabControl.getTabCount() - 1;
1376 if (currentIndex == indexToShow) {
1377 indexToShow--;
1378 }
1379 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08001380 switchTabs(currentIndex, indexToShow, true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001381 break;
1382
1383 case R.id.homepage_menu_id:
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001384 TabControl.Tab current = mTabControl.getCurrentTab();
1385 if (current != null) {
1386 dismissSubWindow(current);
1387 current.getWebView().loadUrl(mSettings.getHomePage());
1388 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001389 break;
1390
1391 case R.id.preferences_menu_id:
1392 Intent intent = new Intent(this,
1393 BrowserPreferencesPage.class);
1394 startActivityForResult(intent, PREFERENCES_PAGE);
1395 break;
1396
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001397 case R.id.find_menu_id:
1398 if (null == mFindDialog) {
1399 mFindDialog = new FindDialog(this);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001400 }
1401 mFindDialog.setWebView(getTopWindow());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001402 mFindDialog.show();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001403 mMenuState = EMPTY_MENU;
1404 break;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001405
The Android Open Source Project96cb4a42009-01-15 16:12:12 -08001406 case R.id.select_text_id:
1407 getTopWindow().emulateShiftHeld();
1408 break;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001409 case R.id.page_info_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001410 showPageInfo(mTabControl.getCurrentTab(), false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001411 break;
1412
The Android Open Source Projected217d92008-12-17 18:05:52 -08001413 case R.id.classic_history_menu_id:
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08001414 bookmarksOrHistoryPicker(true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001415 break;
The Android Open Source Project066e9082009-01-20 14:03:59 -08001416
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001417 case R.id.share_page_menu_id:
1418 Browser.sendString(this, getTopWindow().getUrl());
1419 break;
The Android Open Source Project066e9082009-01-20 14:03:59 -08001420
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001421 case R.id.dump_nav_menu_id:
1422 getTopWindow().debugDump();
1423 break;
1424
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001425 case R.id.zoom_in_menu_id:
1426 getTopWindow().zoomIn();
1427 break;
1428
1429 case R.id.zoom_out_menu_id:
1430 getTopWindow().zoomOut();
1431 break;
1432
1433 case R.id.view_downloads_menu_id:
1434 viewDownloads(null);
1435 break;
The Android Open Source Project066e9082009-01-20 14:03:59 -08001436
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001437 // -- Tab menu
1438 case R.id.view_tab_menu_id:
1439 if (mTabListener != null && mTabOverview != null) {
1440 int pos = mTabOverview.getContextMenuPosition(item);
1441 mTabOverview.setCurrentIndex(pos);
1442 mTabListener.onClick(pos);
1443 }
1444 break;
1445
1446 case R.id.remove_tab_menu_id:
1447 if (mTabListener != null && mTabOverview != null) {
1448 int pos = mTabOverview.getContextMenuPosition(item);
1449 mTabListener.remove(pos);
1450 }
1451 break;
1452
1453 case R.id.new_tab_menu_id:
1454 // No need to check for mTabOverview here since we are not
1455 // dependent on it for a position.
1456 if (mTabListener != null) {
1457 // If the overview happens to be non-null, make the "New
1458 // Tab" cell visible.
1459 if (mTabOverview != null) {
1460 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1461 }
1462 mTabListener.onClick(ImageGrid.NEW_TAB);
1463 }
1464 break;
1465
1466 case R.id.bookmark_tab_menu_id:
1467 if (mTabListener != null && mTabOverview != null) {
1468 int pos = mTabOverview.getContextMenuPosition(item);
1469 TabControl.Tab t = mTabControl.getTab(pos);
1470 // Since we called populatePickerData for all of the
1471 // tabs, getTitle and getUrl will return appropriate
1472 // values.
1473 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1474 t.getUrl());
1475 }
1476 break;
1477
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08001478 case R.id.history_tab_menu_id:
1479 bookmarksOrHistoryPicker(true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001480 break;
1481
1482 case R.id.bookmarks_tab_menu_id:
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08001483 bookmarksOrHistoryPicker(false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001484 break;
1485
1486 case R.id.properties_tab_menu_id:
1487 if (mTabListener != null && mTabOverview != null) {
1488 int pos = mTabOverview.getContextMenuPosition(item);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001489 showPageInfo(mTabControl.getTab(pos), false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001490 }
1491 break;
1492
The Android Open Source Projected217d92008-12-17 18:05:52 -08001493 case R.id.window_one_menu_id:
1494 case R.id.window_two_menu_id:
1495 case R.id.window_three_menu_id:
1496 case R.id.window_four_menu_id:
1497 case R.id.window_five_menu_id:
1498 case R.id.window_six_menu_id:
1499 case R.id.window_seven_menu_id:
1500 case R.id.window_eight_menu_id:
1501 {
1502 int menuid = item.getItemId();
1503 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1504 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1505 TabControl.Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project066e9082009-01-20 14:03:59 -08001506 if (desiredTab != null &&
The Android Open Source Projected217d92008-12-17 18:05:52 -08001507 desiredTab != mTabControl.getCurrentTab()) {
1508 switchTabs(mTabControl.getCurrentIndex(), id, false);
1509 }
1510 break;
The Android Open Source Project066e9082009-01-20 14:03:59 -08001511 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08001512 }
1513 }
1514 break;
The Android Open Source Project066e9082009-01-20 14:03:59 -08001515
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001516 default:
1517 if (!super.onOptionsItemSelected(item)) {
1518 return false;
1519 }
1520 // Otherwise fall through.
1521 }
1522 mCanChord = false;
1523 return true;
1524 }
1525
1526 public void closeFind() {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001527 mMenuState = R.id.MAIN_MENU;
1528 }
1529
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001530 @Override public boolean onPrepareOptionsMenu(Menu menu)
1531 {
1532 // This happens when the user begins to hold down the menu key, so
1533 // allow them to chord to get a shortcut.
1534 mCanChord = true;
1535 // Note: setVisible will decide whether an item is visible; while
1536 // setEnabled() will decide whether an item is enabled, which also means
1537 // whether the matching shortcut key will function.
1538 super.onPrepareOptionsMenu(menu);
1539 switch (mMenuState) {
1540 case R.id.TAB_MENU:
1541 if (mCurrentMenuState != mMenuState) {
1542 menu.setGroupVisible(R.id.MAIN_MENU, false);
1543 menu.setGroupEnabled(R.id.MAIN_MENU, false);
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08001544 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001545 menu.setGroupVisible(R.id.TAB_MENU, true);
1546 menu.setGroupEnabled(R.id.TAB_MENU, true);
1547 }
1548 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1549 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1550 tab.setVisible(newT);
1551 tab.setEnabled(newT);
1552 break;
1553 case EMPTY_MENU:
1554 if (mCurrentMenuState != mMenuState) {
1555 menu.setGroupVisible(R.id.MAIN_MENU, false);
1556 menu.setGroupEnabled(R.id.MAIN_MENU, false);
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08001557 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001558 menu.setGroupVisible(R.id.TAB_MENU, false);
1559 menu.setGroupEnabled(R.id.TAB_MENU, false);
1560 }
1561 break;
1562 default:
1563 if (mCurrentMenuState != mMenuState) {
1564 menu.setGroupVisible(R.id.MAIN_MENU, true);
1565 menu.setGroupEnabled(R.id.MAIN_MENU, true);
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08001566 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001567 menu.setGroupVisible(R.id.TAB_MENU, false);
1568 menu.setGroupEnabled(R.id.TAB_MENU, false);
1569 }
1570 final WebView w = getTopWindow();
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08001571 boolean canGoBack = false;
1572 boolean canGoForward = false;
1573 boolean isHome = false;
1574 if (w != null) {
1575 canGoBack = w.canGoBack();
1576 canGoForward = w.canGoForward();
1577 isHome = mSettings.getHomePage().equals(w.getUrl());
1578 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001579 final MenuItem back = menu.findItem(R.id.back_menu_id);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001580 back.setEnabled(canGoBack);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001581
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001582 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001583 home.setEnabled(!isHome);
1584
1585 menu.findItem(R.id.forward_menu_id)
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08001586 .setEnabled(canGoForward);
The Android Open Source Project066e9082009-01-20 14:03:59 -08001587
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001588 // decide whether to show the share link option
1589 PackageManager pm = getPackageManager();
1590 Intent send = new Intent(Intent.ACTION_SEND);
1591 send.setType("text/plain");
1592 List<ResolveInfo> list = pm.queryIntentActivities(send,
1593 PackageManager.MATCH_DEFAULT_ONLY);
1594 menu.findItem(R.id.share_page_menu_id).setVisible(
1595 list.size() > 0);
The Android Open Source Project066e9082009-01-20 14:03:59 -08001596
The Android Open Source Projected217d92008-12-17 18:05:52 -08001597 // If there is only 1 window, the text will be "New window"
1598 final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1599 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1600 getString(R.string.view_tabs_condensed) :
1601 getString(R.string.tab_picker_new_tab));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001602
1603 boolean isNavDump = mSettings.isNavDump();
1604 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1605 nav.setVisible(isNavDump);
1606 nav.setEnabled(isNavDump);
1607 break;
1608 }
1609 mCurrentMenuState = mMenuState;
1610 return true;
1611 }
1612
1613 @Override
1614 public void onCreateContextMenu(ContextMenu menu, View v,
1615 ContextMenuInfo menuInfo) {
1616 WebView webview = (WebView) v;
1617 WebView.HitTestResult result = webview.getHitTestResult();
1618 if (result == null) {
1619 return;
1620 }
1621
1622 int type = result.getType();
1623 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1624 Log.w(LOGTAG,
1625 "We should not show context menu when nothing is touched");
1626 return;
1627 }
1628 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1629 // let TextView handles context menu
1630 return;
1631 }
1632
1633 // Note, http://b/issue?id=1106666 is requesting that
1634 // an inflated menu can be used again. This is not available
1635 // yet, so inflate each time (yuk!)
1636 MenuInflater inflater = getMenuInflater();
1637 inflater.inflate(R.menu.browsercontext, menu);
1638
1639 // Show the correct menu group
1640 String extra = result.getExtra();
1641 menu.setGroupVisible(R.id.PHONE_MENU,
1642 type == WebView.HitTestResult.PHONE_TYPE);
1643 menu.setGroupVisible(R.id.EMAIL_MENU,
1644 type == WebView.HitTestResult.EMAIL_TYPE);
1645 menu.setGroupVisible(R.id.GEO_MENU,
1646 type == WebView.HitTestResult.GEO_TYPE);
1647 menu.setGroupVisible(R.id.IMAGE_MENU,
The Android Open Source Projected217d92008-12-17 18:05:52 -08001648 type == WebView.HitTestResult.IMAGE_TYPE
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001649 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1650 menu.setGroupVisible(R.id.ANCHOR_MENU,
The Android Open Source Projected217d92008-12-17 18:05:52 -08001651 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001652 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1653
1654 // Setup custom handling depending on the type
1655 switch (type) {
1656 case WebView.HitTestResult.PHONE_TYPE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001657 menu.setHeaderTitle(Uri.decode(extra));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001658 menu.findItem(R.id.dial_context_menu_id).setIntent(
1659 new Intent(Intent.ACTION_VIEW, Uri
1660 .parse(WebView.SCHEME_TEL + extra)));
The Android Open Source Projected217d92008-12-17 18:05:52 -08001661 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1662 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1663 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001664 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1665 addIntent);
1666 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1667 new Copy(extra));
1668 break;
1669
1670 case WebView.HitTestResult.EMAIL_TYPE:
1671 menu.setHeaderTitle(extra);
1672 menu.findItem(R.id.email_context_menu_id).setIntent(
1673 new Intent(Intent.ACTION_VIEW, Uri
1674 .parse(WebView.SCHEME_MAILTO + extra)));
1675 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1676 new Copy(extra));
1677 break;
1678
1679 case WebView.HitTestResult.GEO_TYPE:
1680 menu.setHeaderTitle(extra);
1681 menu.findItem(R.id.map_context_menu_id).setIntent(
1682 new Intent(Intent.ACTION_VIEW, Uri
1683 .parse(WebView.SCHEME_GEO
1684 + URLEncoder.encode(extra))));
1685 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1686 new Copy(extra));
1687 break;
1688
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001689 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1690 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08001691 TextView titleView = (TextView) LayoutInflater.from(this)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001692 .inflate(android.R.layout.browser_link_context_header,
1693 null);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001694 titleView.setText(extra);
1695 menu.setHeaderView(titleView);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001696 // decide whether to show the open link in new tab option
1697 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1698 mTabControl.getTabCount() < TabControl.MAX_TABS);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001699 PackageManager pm = getPackageManager();
1700 Intent send = new Intent(Intent.ACTION_SEND);
1701 send.setType("text/plain");
1702 List<ResolveInfo> list = pm.queryIntentActivities(send,
1703 PackageManager.MATCH_DEFAULT_ONLY);
1704 menu.findItem(R.id.share_link_context_menu_id).setVisible(
1705 list.size() > 0);
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08001706 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1707 break;
1708 }
1709 // otherwise fall through to handle image part
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001710 case WebView.HitTestResult.IMAGE_TYPE:
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08001711 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1712 menu.setHeaderTitle(extra);
1713 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08001714 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1715 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1716 menu.findItem(R.id.download_context_menu_id).
1717 setOnMenuItemClickListener(new Download(extra));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001718 break;
1719
1720 default:
1721 Log.w(LOGTAG, "We should not get here.");
1722 break;
1723 }
1724 }
1725
1726 // Used by attachTabToContentView for the WebView's ZoomControl widget.
1727 private static final FrameLayout.LayoutParams ZOOM_PARAMS =
1728 new FrameLayout.LayoutParams(
1729 ViewGroup.LayoutParams.FILL_PARENT,
1730 ViewGroup.LayoutParams.WRAP_CONTENT,
1731 Gravity.BOTTOM);
1732
1733 // Attach the given tab to the content view.
1734 private void attachTabToContentView(TabControl.Tab t) {
1735 final WebView main = t.getWebView();
1736 // Attach the main WebView.
1737 mContentView.addView(main, COVER_SCREEN_PARAMS);
1738 // Attach the Zoom control widget and hide it.
1739 final View zoom = main.getZoomControls();
1740 mContentView.addView(zoom, ZOOM_PARAMS);
1741 zoom.setVisibility(View.GONE);
1742 // Attach the sub window if necessary
1743 attachSubWindow(t);
1744 // Request focus on the top window.
1745 t.getTopWindow().requestFocus();
1746 }
1747
1748 // Attach a sub window to the main WebView of the given tab.
1749 private void attachSubWindow(TabControl.Tab t) {
1750 // If a sub window exists, attach it to the content view.
1751 final WebView subView = t.getSubWebView();
1752 if (subView != null) {
1753 final View container = t.getSubWebViewContainer();
1754 mContentView.addView(container, COVER_SCREEN_PARAMS);
1755 subView.requestFocus();
1756 }
1757 }
1758
1759 // Remove the given tab from the content view.
1760 private void removeTabFromContentView(TabControl.Tab t) {
1761 // Remove the Zoom widget and the main WebView.
1762 mContentView.removeView(t.getWebView().getZoomControls());
1763 mContentView.removeView(t.getWebView());
1764 // Remove the sub window if it exists.
1765 if (t.getSubWebView() != null) {
1766 mContentView.removeView(t.getSubWebViewContainer());
1767 }
1768 }
1769
1770 // Remove the sub window if it exists. Also called by TabControl when the
1771 // user clicks the 'X' to dismiss a sub window.
1772 /* package */ void dismissSubWindow(TabControl.Tab t) {
1773 final WebView mainView = t.getWebView();
1774 if (t.getSubWebView() != null) {
1775 // Remove the container view and request focus on the main WebView.
1776 mContentView.removeView(t.getSubWebViewContainer());
1777 mainView.requestFocus();
1778 // Tell the TabControl to dismiss the subwindow. This will destroy
1779 // the WebView.
1780 mTabControl.dismissSubWindow(t);
1781 }
1782 }
1783
1784 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
1785 private void sendAnimateFromOverview(final TabControl.Tab tab,
1786 final boolean newTab, final String url, final int delay,
1787 final Message msg) {
1788 // Set the current tab.
1789 mTabControl.setCurrentTab(tab);
1790 // Attach the WebView so it will layout.
1791 attachTabToContentView(tab);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001792 // Set the view to invisibile for now.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001793 tab.getWebView().setVisibility(View.INVISIBLE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001794 // If there is a sub window, make it invisible too.
1795 if (tab.getSubWebView() != null) {
1796 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
1797 }
1798 // Create our fake animating view.
1799 final AnimatingView view = new AnimatingView(this, tab);
1800 // Attach it to the view system and make in invisible so it will
1801 // layout but not flash white on the screen.
1802 mContentView.addView(view, COVER_SCREEN_PARAMS);
1803 view.setVisibility(View.INVISIBLE);
1804 // Send the animate message.
1805 final HashMap map = new HashMap();
1806 map.put("view", view);
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08001807 // Load the url after the AnimatingView has captured the picture. This
1808 // prevents any bad layout or bad scale from being used during
1809 // animation.
1810 if (url != null) {
1811 dismissSubWindow(tab);
1812 tab.getWebView().loadUrl(url);
1813 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001814 map.put("msg", msg);
1815 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1816 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
1817 // Increment the count to indicate that we are in an animation.
1818 mAnimationCount++;
1819 // Remove the listener so we don't get any more tab changes.
The Android Open Source Projected217d92008-12-17 18:05:52 -08001820 mTabOverview.setListener(null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001821 mTabListener = null;
The Android Open Source Projected217d92008-12-17 18:05:52 -08001822 // Make the menu empty until the animation completes.
1823 mMenuState = EMPTY_MENU;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001824
1825 }
1826
1827 // 500ms animation with 800ms delay
1828 private static final int TAB_ANIMATION_DURATION = 500;
1829 private static final int TAB_OVERVIEW_DELAY = 800;
1830
1831 // Called by TabControl when a tab is requesting focus
1832 /* package */ void showTab(TabControl.Tab t) {
1833 // Disallow focus change during a tab animation.
1834 if (mAnimationCount > 0) {
1835 return;
1836 }
1837 int delay = 0;
1838 if (mTabOverview == null) {
1839 // Add a delay so the tab overview can be shown before the second
1840 // animation begins.
1841 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1842 tabPicker(false, mTabControl.getTabIndex(t), false);
1843 }
1844 sendAnimateFromOverview(t, false, null, delay, null);
1845 }
1846
1847 // This method does a ton of stuff. It will attempt to create a new tab
1848 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1849 // url isn't null, it will load the given url. If the tab overview is not
1850 // showing, it will animate to the tab overview, create a new tab and
1851 // animate away from it. After the animation completes, it will dispatch
1852 // the given Message. If the tab overview is already showing (i.e. this
1853 // method is called from TabListener.onClick(), the method will animate
1854 // away from the tab overview.
The Android Open Source Projected217d92008-12-17 18:05:52 -08001855 private void openTabAndShow(String url, final Message msg,
1856 boolean closeOnExit) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001857 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1858 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1859 if (newTab) {
1860 int delay = 0;
1861 // If the tab overview is up and there are animations, just load
1862 // the url.
1863 if (mTabOverview != null && mAnimationCount > 0) {
1864 if (url != null) {
1865 // We should not have a msg here since onCreateWindow
1866 // checks the animation count and every other caller passes
1867 // null.
1868 assert msg == null;
1869 // just dismiss the subwindow and load the given url.
1870 dismissSubWindow(currentTab);
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001871 currentTab.getWebView().loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001872 }
1873 } else {
1874 // show mTabOverview if it is not there.
1875 if (mTabOverview == null) {
1876 // We have to delay the animation from the tab picker by the
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001877 // length of the tab animation. Add a delay so the tab
1878 // overview can be shown before the second animation begins.
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001879 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1880 tabPicker(false, ImageGrid.NEW_TAB, false);
1881 }
1882 // Animate from the Tab overview after any animations have
1883 // finished.
The Android Open Source Projected217d92008-12-17 18:05:52 -08001884 sendAnimateFromOverview(mTabControl.createNewTab(closeOnExit),
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001885 true, url, delay, msg);
1886 }
1887 } else if (url != null) {
1888 // We should not have a msg here.
1889 assert msg == null;
1890 if (mTabOverview != null && mAnimationCount == 0) {
1891 sendAnimateFromOverview(currentTab, false, url,
1892 TAB_OVERVIEW_DELAY, null);
1893 } else {
1894 // Get rid of the subwindow if it exists
1895 dismissSubWindow(currentTab);
1896 // Load the given url.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08001897 currentTab.getWebView().loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001898 }
1899 }
1900 }
1901
1902 private Animation createTabAnimation(final AnimatingView view,
1903 final View cell, boolean scaleDown) {
1904 final AnimationSet set = new AnimationSet(true);
1905 final float scaleX = (float) cell.getWidth() / view.getWidth();
1906 final float scaleY = (float) cell.getHeight() / view.getHeight();
1907 if (scaleDown) {
1908 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
1909 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
1910 cell.getTop()));
1911 } else {
1912 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
1913 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
1914 cell.getTop(), 0));
1915 }
1916 set.setDuration(TAB_ANIMATION_DURATION);
1917 set.setInterpolator(new DecelerateInterpolator());
1918 return set;
1919 }
1920
1921 // Animate to the tab overview. currentIndex tells us which position to
1922 // animate to and newIndex is the position that should be selected after
1923 // the animation completes.
1924 // If remove is true, after the animation stops, a confirmation dialog will
1925 // be displayed to the user.
1926 private void animateToTabOverview(final int newIndex, final boolean remove,
1927 final AnimatingView view) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001928 // Find the view in the ImageGrid allowing for the "New Tab" cell.
1929 int position = mTabControl.getTabIndex(view.mTab);
1930 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
1931 position++;
1932 }
1933
1934 // Offset the tab position with the first visible position to get a
1935 // number between 0 and 3.
1936 position -= mTabOverview.getFirstVisiblePosition();
1937
1938 // Grab the view that we are going to animate to.
1939 final View v = mTabOverview.getChildAt(position);
1940
1941 final Animation.AnimationListener l =
1942 new Animation.AnimationListener() {
1943 public void onAnimationStart(Animation a) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08001944 mTabOverview.requestFocus();
1945 // Clear the listener so we don't trigger a tab
1946 // selection.
1947 mTabOverview.setListener(null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001948 }
1949 public void onAnimationRepeat(Animation a) {}
1950 public void onAnimationEnd(Animation a) {
1951 // We are no longer animating so decrement the count.
1952 mAnimationCount--;
1953 // Make the view GONE so that it will not draw between
1954 // now and when the Runnable is handled.
1955 view.setVisibility(View.GONE);
1956 // Post a runnable since we can't modify the view
1957 // hierarchy during this callback.
1958 mHandler.post(new Runnable() {
1959 public void run() {
1960 // Remove the AnimatingView.
1961 mContentView.removeView(view);
The Android Open Source Projected217d92008-12-17 18:05:52 -08001962 // Make newIndex visible.
1963 mTabOverview.setCurrentIndex(newIndex);
1964 // Restore the listener.
1965 mTabOverview.setListener(mTabListener);
1966 // Change the menu to TAB_MENU if the
1967 // ImageGrid is interactive.
1968 if (mTabOverview.isLive()) {
1969 mMenuState = R.id.TAB_MENU;
1970 mTabOverview.requestFocus();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001971 }
1972 // If a remove was requested, remove the tab.
1973 if (remove) {
1974 // During a remove, the current tab has
1975 // already changed. Remember the current one
1976 // here.
1977 final TabControl.Tab currentTab =
1978 mTabControl.getCurrentTab();
1979 // Remove the tab at newIndex from
1980 // TabControl and the tab overview.
1981 final TabControl.Tab tab =
1982 mTabControl.getTab(newIndex);
1983 mTabControl.removeTab(tab);
1984 // Restore the current tab.
1985 if (currentTab != tab) {
1986 mTabControl.setCurrentTab(currentTab);
1987 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08001988 mTabOverview.remove(newIndex);
1989 // Make the current tab visible.
1990 mTabOverview.setCurrentIndex(
1991 mTabControl.getCurrentIndex());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07001992 }
1993 }
1994 });
1995 }
1996 };
1997
1998 // Do an animation if there is a view to animate to.
1999 if (v != null) {
2000 // Create our animation
2001 final Animation anim = createTabAnimation(view, v, true);
2002 anim.setAnimationListener(l);
2003 // Start animating
2004 view.startAnimation(anim);
2005 } else {
2006 // If something goes wrong and we didn't find a view to animate to,
2007 // just do everything here.
2008 l.onAnimationStart(null);
2009 l.onAnimationEnd(null);
2010 }
2011 }
2012
2013 // Animate from the tab picker. The index supplied is the index to animate
2014 // from.
2015 private void animateFromTabOverview(final AnimatingView view,
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08002016 final boolean newTab, final Message msg) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002017 // firstVisible is the first visible tab on the screen. This helps
2018 // to know which corner of the screen the selected tab is.
2019 int firstVisible = mTabOverview.getFirstVisiblePosition();
2020 // tabPosition is the 0-based index of of the tab being opened
2021 int tabPosition = mTabControl.getTabIndex(view.mTab);
2022 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2023 // Add one to make room for the "New Tab" cell.
2024 tabPosition++;
2025 }
2026 // If this is a new tab, animate from the "New Tab" cell.
2027 if (newTab) {
2028 tabPosition = 0;
2029 }
2030 // Location corresponds to the four corners of the screen.
2031 // A new tab or 0 is upper left, 0 for an old tab is upper
2032 // right, 1 is lower left, and 2 is lower right
2033 int location = tabPosition - firstVisible;
2034
2035 // Find the view at this location.
2036 final View v = mTabOverview.getChildAt(location);
2037
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08002038 // Wait until the animation completes to replace the AnimatingView.
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002039 final Animation.AnimationListener l =
2040 new Animation.AnimationListener() {
2041 public void onAnimationStart(Animation a) {}
2042 public void onAnimationRepeat(Animation a) {}
2043 public void onAnimationEnd(Animation a) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002044 mHandler.post(new Runnable() {
2045 public void run() {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002046 mContentView.removeView(view);
2047 // Dismiss the tab overview. If the cell at the
2048 // given location is null, set the fade
2049 // parameter to true.
2050 dismissTabOverview(v == null);
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002051 TabControl.Tab t =
2052 mTabControl.getCurrentTab();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002053 mMenuState = R.id.MAIN_MENU;
2054 // Resume regular updates.
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08002055 t.getWebView().resumeTimers();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002056 // Dispatch the message after the animation
2057 // completes.
2058 if (msg != null) {
2059 msg.sendToTarget();
2060 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002061 // The animation is done and the tab overview is
2062 // gone so allow key events and other animations
2063 // to begin.
2064 mAnimationCount--;
2065 // Reset all the title bar info.
2066 resetTitle();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002067 }
2068 });
2069 }
2070 };
2071
2072 if (v != null) {
2073 final Animation anim = createTabAnimation(view, v, false);
2074 // Set the listener and start animating
2075 anim.setAnimationListener(l);
2076 view.startAnimation(anim);
2077 // Make the view VISIBLE during the animation.
2078 view.setVisibility(View.VISIBLE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002079 } else {
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08002080 // Go ahead and do all the cleanup.
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002081 l.onAnimationEnd(null);
2082 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002083 }
2084
2085 // Dismiss the tab overview applying a fade if needed.
2086 private void dismissTabOverview(final boolean fade) {
2087 if (fade) {
2088 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2089 anim.setDuration(500);
2090 anim.startNow();
2091 mTabOverview.startAnimation(anim);
2092 }
2093 // Just in case there was a problem with animating away from the tab
2094 // overview
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002095 mTabControl.getCurrentWebView().setVisibility(View.VISIBLE);
The Android Open Source Projected217d92008-12-17 18:05:52 -08002096 // Make the sub window container visible.
2097 if (mTabControl.getCurrentSubWindow() != null) {
2098 mTabControl.getCurrentTab().getSubWebViewContainer()
2099 .setVisibility(View.VISIBLE);
2100 }
2101 mContentView.removeView(mTabOverview);
2102 mTabOverview.clear();
2103 mTabOverview = null;
2104 mTabListener = null;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002105 }
2106
2107 private void openTab(String url) {
2108 if (mSettings.openInBackground()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002109 TabControl.Tab t = mTabControl.createNewTab(false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002110 if (t != null) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002111 t.getWebView().loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002112 }
2113 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002114 openTabAndShow(url, null, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002115 }
2116 }
2117
2118 private class Copy implements OnMenuItemClickListener {
2119 private CharSequence mText;
2120
2121 public boolean onMenuItemClick(MenuItem item) {
2122 copy(mText);
2123 return true;
2124 }
2125
2126 public Copy(CharSequence toCopy) {
2127 mText = toCopy;
2128 }
2129 }
The Android Open Source Project066e9082009-01-20 14:03:59 -08002130
The Android Open Source Projected217d92008-12-17 18:05:52 -08002131 private class Download implements OnMenuItemClickListener {
2132 private String mText;
2133
2134 public boolean onMenuItemClick(MenuItem item) {
2135 onDownloadStartNoStream(mText, null, null, null, -1);
2136 return true;
2137 }
2138
2139 public Download(String toDownload) {
2140 mText = toDownload;
2141 }
2142 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002143
2144 private void copy(CharSequence text) {
2145 try {
2146 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2147 if (clip != null) {
2148 clip.setClipboardText(text);
2149 }
2150 } catch (android.os.RemoteException e) {
2151 Log.e(LOGTAG, "Copy failed", e);
2152 }
2153 }
2154
2155 /**
2156 * Resets the browser title-view to whatever it must be (for example, if we
2157 * load a page from history).
2158 */
2159 private void resetTitle() {
2160 resetLockIcon();
2161 resetTitleIconAndProgress();
2162 }
2163
2164 /**
2165 * Resets the browser title-view to whatever it must be
2166 * (for example, if we had a loading error)
2167 * When we have a new page, we call resetTitle, when we
2168 * have to reset the titlebar to whatever it used to be
2169 * (for example, if the user chose to stop loading), we
2170 * call resetTitleAndRevertLockIcon.
2171 */
2172 /* package */ void resetTitleAndRevertLockIcon() {
2173 revertLockIcon();
2174 resetTitleIconAndProgress();
2175 }
2176
2177 /**
2178 * Reset the title, favicon, and progress.
2179 */
2180 private void resetTitleIconAndProgress() {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002181 WebView current = mTabControl.getCurrentWebView();
2182 if (current == null) {
2183 return;
2184 }
2185 resetTitleAndIcon(current);
2186 int progress = current.getProgress();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002187 mInLoad = (progress != 100);
2188 updateInLoadMenuItems();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002189 mWebChromeClient.onProgressChanged(current, progress);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002190 }
2191
2192 // Reset the title and the icon based on the given item.
2193 private void resetTitleAndIcon(WebView view) {
2194 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2195 if (item != null) {
2196 setUrlTitle(item.getUrl(), item.getTitle());
2197 setFavicon(item.getFavicon());
2198 } else {
2199 setUrlTitle(null, null);
2200 setFavicon(null);
2201 }
2202 }
2203
2204 /**
2205 * Sets a title composed of the URL and the title string.
2206 * @param url The URL of the site being loaded.
2207 * @param title The title of the site being loaded.
2208 */
2209 private void setUrlTitle(String url, String title) {
2210 mUrl = url;
2211 mTitle = title;
2212
The Android Open Source Projected217d92008-12-17 18:05:52 -08002213 // While the tab overview is animating or being shown, block changes
2214 // to the title.
2215 if (mAnimationCount == 0 && mTabOverview == null) {
2216 setTitle(buildUrlTitle(url, title));
2217 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002218 }
2219
2220 /**
2221 * Builds and returns the page title, which is some
2222 * combination of the page URL and title.
2223 * @param url The URL of the site being loaded.
2224 * @param title The title of the site being loaded.
2225 * @return The page title.
2226 */
2227 private String buildUrlTitle(String url, String title) {
2228 String urlTitle = "";
2229
2230 if (url != null) {
2231 String titleUrl = buildTitleUrl(url);
2232
2233 if (title != null && 0 < title.length()) {
2234 if (titleUrl != null && 0 < titleUrl.length()) {
2235 urlTitle = titleUrl + ": " + title;
2236 } else {
2237 urlTitle = title;
2238 }
2239 } else {
2240 if (titleUrl != null) {
2241 urlTitle = titleUrl;
2242 }
2243 }
2244 }
2245
2246 return urlTitle;
2247 }
2248
2249 /**
2250 * @param url The URL to build a title version of the URL from.
2251 * @return The title version of the URL or null if fails.
2252 * The title version of the URL can be either the URL hostname,
2253 * or the hostname with an "https://" prefix (for secure URLs),
2254 * or an empty string if, for example, the URL in question is a
2255 * file:// URL with no hostname.
2256 */
2257 private static String buildTitleUrl(String url) {
2258 String titleUrl = null;
2259
2260 if (url != null) {
2261 try {
2262 // parse the url string
2263 URL urlObj = new URL(url);
2264 if (urlObj != null) {
2265 titleUrl = "";
2266
2267 String protocol = urlObj.getProtocol();
2268 String host = urlObj.getHost();
2269
2270 if (host != null && 0 < host.length()) {
2271 titleUrl = host;
2272 if (protocol != null) {
2273 // if a secure site, add an "https://" prefix!
2274 if (protocol.equalsIgnoreCase("https")) {
2275 titleUrl = protocol + "://" + host;
2276 }
2277 }
2278 }
2279 }
2280 } catch (MalformedURLException e) {}
2281 }
2282
2283 return titleUrl;
2284 }
2285
2286 // Set the favicon in the title bar.
2287 private void setFavicon(Bitmap icon) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002288 // While the tab overview is animating or being shown, block changes to
2289 // the favicon.
2290 if (mAnimationCount > 0 || mTabOverview != null) {
2291 return;
2292 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002293 Drawable[] array = new Drawable[2];
2294 PaintDrawable p = new PaintDrawable(Color.WHITE);
2295 p.setCornerRadius(3f);
2296 array[0] = p;
2297 if (icon == null) {
2298 array[1] = mGenericFavicon;
2299 } else {
2300 array[1] = new BitmapDrawable(icon);
2301 }
2302 LayerDrawable d = new LayerDrawable(array);
2303 d.setLayerInset(1, 2, 2, 2, 2);
2304 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
2305 }
2306
2307 /**
2308 * Saves the current lock-icon state before resetting
2309 * the lock icon. If we have an error, we may need to
2310 * roll back to the previous state.
2311 */
2312 private void saveLockIcon() {
2313 mPrevLockType = mLockIconType;
2314 }
2315
2316 /**
2317 * Reverts the lock-icon state to the last saved state,
2318 * for example, if we had an error, and need to cancel
2319 * the load.
2320 */
2321 private void revertLockIcon() {
2322 mLockIconType = mPrevLockType;
2323
2324 if (Config.LOGV) {
2325 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2326 " revert lock icon to " + mLockIconType);
2327 }
2328
2329 updateLockIconImage(mLockIconType);
2330 }
2331
The Android Open Source Projected217d92008-12-17 18:05:52 -08002332 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002333 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2334 // Animate to the tab picker, remove the current tab, then
2335 // animate away from the tab picker to the parent WebView.
The Android Open Source Projected217d92008-12-17 18:05:52 -08002336 tabPicker(false, indexFrom, remove);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002337 // Change to the parent tab
2338 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2339 if (tab != null) {
2340 sendAnimateFromOverview(tab, false, null, delay, null);
2341 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002342 // Increment this here so that no other animations can happen in
2343 // between the end of the tab picker transition and the beginning
2344 // of openTabAndShow. This has a matching decrement in the handler
2345 // of OPEN_TAB_AND_SHOW.
2346 mAnimationCount++;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002347 // Send a message to open a new tab.
2348 mHandler.sendMessageDelayed(
2349 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2350 mSettings.getHomePage()), delay);
2351 }
2352 }
2353
2354 private void goBackOnePageOrQuit() {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002355 TabControl.Tab current = mTabControl.getCurrentTab();
2356 if (current == null) {
2357 /*
2358 * Instead of finishing the activity, simply push this to the back
2359 * of the stack and let ActivityManager to choose the foreground
2360 * activity. As BrowserActivity is singleTask, it will be always the
2361 * root of the task. So we can use either true or false for
2362 * moveTaskToBack().
2363 */
2364 moveTaskToBack(true);
2365 }
2366 WebView w = current.getWebView();
2367 if (w.canGoBack()) {
2368 w.goBack();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002369 } else {
2370 // Check to see if we are closing a window that was created by
2371 // another window. If so, we switch back to that window.
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002372 TabControl.Tab parent = current.getParentTab();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002373 if (parent != null) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002374 switchTabs(mTabControl.getCurrentIndex(),
2375 mTabControl.getTabIndex(parent), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002376 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002377 if (current.closeOnExit()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08002378 if (mTabControl.getTabCount() == 1) {
2379 finish();
2380 return;
2381 }
2382 // call pauseWebView() now, we won't be able to call it in
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002383 // onPause() as the WebView won't be valid.
The Android Open Source Projected217d92008-12-17 18:05:52 -08002384 pauseWebView();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002385 removeTabFromContentView(current);
2386 mTabControl.removeTab(current);
The Android Open Source Projected217d92008-12-17 18:05:52 -08002387 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002388 /*
2389 * Instead of finishing the activity, simply push this to the back
2390 * of the stack and let ActivityManager to choose the foreground
2391 * activity. As BrowserActivity is singleTask, it will be always the
2392 * root of the task. So we can use either true or false for
2393 * moveTaskToBack().
2394 */
2395 moveTaskToBack(true);
2396 }
2397 }
2398 }
2399
2400 public KeyTracker.State onKeyTracker(int keyCode,
2401 KeyEvent event,
2402 KeyTracker.Stage stage,
2403 int duration) {
2404 // if onKeyTracker() is called after activity onStop()
2405 // because of accumulated key events,
2406 // we should ignore it as browser is not active any more.
2407 WebView topWindow = getTopWindow();
2408 if (topWindow == null)
2409 return KeyTracker.State.NOT_TRACKING;
2410
2411 if (keyCode == KeyEvent.KEYCODE_BACK) {
2412 // During animations, block the back key so that other animations
2413 // are not triggered and so that we don't end up destroying all the
2414 // WebViews before finishing the animation.
2415 if (mAnimationCount > 0) {
2416 return KeyTracker.State.DONE_TRACKING;
2417 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002418 if (stage == KeyTracker.Stage.LONG_REPEAT) {
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08002419 bookmarksOrHistoryPicker(true);
The Android Open Source Projected217d92008-12-17 18:05:52 -08002420 return KeyTracker.State.DONE_TRACKING;
2421 } else if (stage == KeyTracker.Stage.UP) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002422 // FIXME: Currently, we do not have a notion of the
2423 // history picker for the subwindow, but maybe we
2424 // should?
2425 WebView subwindow = mTabControl.getCurrentSubWindow();
2426 if (subwindow != null) {
2427 if (subwindow.canGoBack()) {
2428 subwindow.goBack();
2429 } else {
2430 dismissSubWindow(mTabControl.getCurrentTab());
2431 }
2432 } else {
2433 goBackOnePageOrQuit();
2434 }
2435 return KeyTracker.State.DONE_TRACKING;
2436 }
2437 return KeyTracker.State.KEEP_TRACKING;
2438 }
2439 return KeyTracker.State.NOT_TRACKING;
2440 }
2441
2442 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2443 if (keyCode == KeyEvent.KEYCODE_MENU) {
2444 mMenuIsDown = true;
2445 }
2446 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2447 if (!handled) {
2448 switch (keyCode) {
2449 case KeyEvent.KEYCODE_SPACE:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002450 if (event.isShiftPressed()) {
2451 getTopWindow().pageUp(false);
2452 } else {
2453 getTopWindow().pageDown(false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002454 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002455 handled = true;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002456 break;
2457
2458 default:
2459 break;
2460 }
2461 }
2462 return handled || super.onKeyDown(keyCode, event);
2463 }
2464
2465 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2466 if (keyCode == KeyEvent.KEYCODE_MENU) {
2467 mMenuIsDown = false;
2468 }
2469 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2470 }
2471
2472 private void stopLoading() {
2473 resetTitleAndRevertLockIcon();
2474 WebView w = getTopWindow();
2475 w.stopLoading();
2476 mWebViewClient.onPageFinished(w, w.getUrl());
2477
2478 cancelStopToast();
2479 mStopToast = Toast
2480 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2481 mStopToast.show();
2482 }
2483
2484 private void cancelStopToast() {
2485 if (mStopToast != null) {
2486 mStopToast.cancel();
2487 mStopToast = null;
2488 }
2489 }
2490
2491 // called by a non-UI thread to post the message
2492 public void postMessage(int what, int arg1, int arg2, Object obj) {
2493 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2494 }
2495
2496 // public message ids
2497 public final static int LOAD_URL = 1001;
2498 public final static int STOP_LOAD = 1002;
2499
2500 // Message Ids
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002501 private static final int FOCUS_NODE_HREF = 102;
The Android Open Source Projected217d92008-12-17 18:05:52 -08002502 private static final int CANCEL_CREDS_REQUEST = 103;
2503 private static final int ANIMATE_FROM_OVERVIEW = 104;
2504 private static final int ANIMATE_TO_OVERVIEW = 105;
2505 private static final int OPEN_TAB_AND_SHOW = 106;
2506 private static final int CHECK_MEMORY = 107;
2507 private static final int RELEASE_WAKELOCK = 108;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002508
2509 // Private handler for handling javascript and saving passwords
2510 private Handler mHandler = new Handler() {
2511
2512 public void handleMessage(Message msg) {
2513 switch (msg.what) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002514 case ANIMATE_FROM_OVERVIEW:
2515 final HashMap map = (HashMap) msg.obj;
2516 animateFromTabOverview((AnimatingView) map.get("view"),
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08002517 msg.arg1 == 1, (Message) map.get("msg"));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002518 break;
2519
2520 case ANIMATE_TO_OVERVIEW:
2521 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2522 (AnimatingView) msg.obj);
2523 break;
2524
2525 case OPEN_TAB_AND_SHOW:
The Android Open Source Project765e7c92009-01-09 17:51:25 -08002526 // Decrement mAnimationCount before openTabAndShow because
2527 // the method relies on the value being 0 to start the next
2528 // animation.
2529 mAnimationCount--;
The Android Open Source Projected217d92008-12-17 18:05:52 -08002530 openTabAndShow((String) msg.obj, null, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002531 break;
2532
2533 case FOCUS_NODE_HREF:
2534 String url = (String) msg.getData().get("url");
2535 if (url == null || url.length() == 0) {
2536 break;
2537 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08002538 HashMap focusNodeMap = (HashMap) msg.obj;
2539 WebView view = (WebView) focusNodeMap.get("webview");
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002540 // Only apply the action if the top window did not change.
2541 if (getTopWindow() != view) {
2542 break;
2543 }
2544 switch (msg.arg1) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002545 case R.id.open_context_menu_id:
2546 case R.id.view_image_context_menu_id:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002547 loadURL(getTopWindow(), url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002548 break;
2549 case R.id.open_newtab_context_menu_id:
2550 openTab(url);
2551 break;
2552 case R.id.bookmark_context_menu_id:
2553 Intent intent = new Intent(BrowserActivity.this,
2554 AddBookmarkPage.class);
2555 intent.putExtra("url", url);
2556 startActivity(intent);
2557 break;
2558 case R.id.share_link_context_menu_id:
2559 Browser.sendString(BrowserActivity.this, url);
2560 break;
2561 case R.id.copy_link_context_menu_id:
2562 copy(url);
2563 break;
2564 case R.id.save_link_context_menu_id:
2565 case R.id.download_context_menu_id:
2566 onDownloadStartNoStream(url, null, null, null, -1);
2567 break;
2568 }
2569 break;
2570
2571 case LOAD_URL:
The Android Open Source Projected217d92008-12-17 18:05:52 -08002572 loadURL(getTopWindow(), (String) msg.obj);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002573 break;
2574
2575 case STOP_LOAD:
2576 stopLoading();
2577 break;
2578
2579 case CANCEL_CREDS_REQUEST:
2580 resumeAfterCredentials();
2581 break;
2582
2583 case CHECK_MEMORY:
2584 // reschedule to check memory condition
2585 mHandler.removeMessages(CHECK_MEMORY);
2586 mHandler.sendMessageDelayed(mHandler.obtainMessage
2587 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2588 checkMemory();
2589 break;
2590
2591 case RELEASE_WAKELOCK:
2592 if (mWakeLock.isHeld()) {
2593 mWakeLock.release();
2594 }
2595 break;
2596 }
2597 }
2598 };
2599
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002600 // -------------------------------------------------------------------------
2601 // WebViewClient implementation.
2602 //-------------------------------------------------------------------------
2603
2604 // Use in overrideUrlLoading
2605 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2606 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2607 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2608 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2609
2610 /* package */ WebViewClient getWebViewClient() {
2611 return mWebViewClient;
2612 }
2613
The Android Open Source Projected217d92008-12-17 18:05:52 -08002614 private void updateIcon(String url, Bitmap icon) {
2615 if (icon != null) {
2616 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2617 url, icon);
2618 }
2619 setFavicon(icon);
2620 }
2621
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002622 private final WebViewClient mWebViewClient = new WebViewClient() {
2623 @Override
2624 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2625 resetLockIcon(url);
2626 setUrlTitle(url, null);
The Android Open Source Projected217d92008-12-17 18:05:52 -08002627 // Call updateIcon instead of setFavicon so the bookmark
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002628 // database can be updated.
The Android Open Source Projected217d92008-12-17 18:05:52 -08002629 updateIcon(url, favicon);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002630
2631 if (mSettings.isTracing() == true) {
2632 // FIXME: we should save the trace file somewhere other than data.
2633 // I can't use "/tmp" as it competes for system memory.
2634 File file = getDir("browserTrace", 0);
2635 String baseDir = file.getPath();
2636 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2637 String host;
2638 try {
2639 WebAddress uri = new WebAddress(url);
2640 host = uri.mHost;
2641 } catch (android.net.ParseException ex) {
2642 host = "unknown_host";
2643 }
2644 host = host.replace('.', '_');
2645 baseDir = baseDir + host;
2646 file = new File(baseDir+".data");
2647 if (file.exists() == true) {
2648 file.delete();
2649 }
2650 file = new File(baseDir+".key");
2651 if (file.exists() == true) {
2652 file.delete();
2653 }
2654 mInTrace = true;
2655 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2656 }
2657
2658 // Performance probe
2659 if (false) {
2660 mStart = SystemClock.uptimeMillis();
2661 mProcessStart = Process.getElapsedCpuTime();
2662 long[] sysCpu = new long[7];
2663 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2664 sysCpu, null)) {
2665 mUserStart = sysCpu[0] + sysCpu[1];
2666 mSystemStart = sysCpu[2];
2667 mIdleStart = sysCpu[3];
2668 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2669 }
2670 mUiStart = SystemClock.currentThreadTimeMillis();
2671 }
2672
2673 if (!mPageStarted) {
2674 mPageStarted = true;
2675 // if onResume() has been called, resumeWebView() does nothing.
2676 resumeWebView();
2677 }
2678
2679 // reset sync timer to avoid sync starts during loading a page
2680 CookieSyncManager.getInstance().resetSync();
2681
2682 mInLoad = true;
2683 updateInLoadMenuItems();
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08002684 if (!mIsNetworkUp) {
2685 if ( mAlertDialog == null) {
2686 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2687 .setTitle(R.string.loadSuspendedTitle)
2688 .setMessage(R.string.loadSuspended)
2689 .setPositiveButton(R.string.ok, null)
2690 .show();
2691 }
2692 if (view != null) {
2693 view.setNetworkAvailable(false);
2694 }
2695 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002696
2697 // schedule to check memory condition
2698 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
2699 CHECK_MEMORY_INTERVAL);
2700 }
2701
2702 @Override
2703 public void onPageFinished(WebView view, String url) {
2704 // Reset the title and icon in case we stopped a provisional
2705 // load.
2706 resetTitleAndIcon(view);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002707
2708 // Update the lock icon image only once we are done loading
2709 updateLockIconImage(mLockIconType);
2710
2711 // Performance probe
2712 if (false) {
2713 long[] sysCpu = new long[7];
2714 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2715 sysCpu, null)) {
2716 String uiInfo = "UI thread used "
2717 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2718 + " ms";
2719 if (Config.LOGD) {
2720 Log.d(LOGTAG, uiInfo);
2721 }
2722 //The string that gets written to the log
2723 String performanceString = "It took total "
2724 + (SystemClock.uptimeMillis() - mStart)
2725 + " ms clock time to load the page."
2726 + "\nbrowser process used "
2727 + (Process.getElapsedCpuTime() - mProcessStart)
2728 + " ms, user processes used "
2729 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2730 + " ms, kernel used "
2731 + (sysCpu[2] - mSystemStart) * 10
2732 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2733 + " ms and irq took "
2734 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2735 * 10 + " ms, " + uiInfo;
2736 if (Config.LOGD) {
2737 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2738 }
2739 if (url != null) {
2740 // strip the url to maintain consistency
2741 String newUrl = new String(url);
2742 if (newUrl.startsWith("http://www.")) {
2743 newUrl = newUrl.substring(11);
2744 } else if (newUrl.startsWith("http://")) {
2745 newUrl = newUrl.substring(7);
2746 } else if (newUrl.startsWith("https://www.")) {
2747 newUrl = newUrl.substring(12);
2748 } else if (newUrl.startsWith("https://")) {
2749 newUrl = newUrl.substring(8);
2750 }
2751 if (Config.LOGD) {
2752 Log.d(LOGTAG, newUrl + " loaded");
2753 }
2754 /*
2755 if (sWhiteList.contains(newUrl)) {
2756 // The string that gets pushed to the statistcs
2757 // service
2758 performanceString = performanceString
2759 + "\nWebpage: "
2760 + newUrl
2761 + "\nCarrier: "
2762 + android.os.SystemProperties
2763 .get("gsm.sim.operator.alpha");
2764 if (mWebView != null
2765 && mWebView.getContext() != null
2766 && mWebView.getContext().getSystemService(
2767 Context.CONNECTIVITY_SERVICE) != null) {
The Android Open Source Project066e9082009-01-20 14:03:59 -08002768 ConnectivityManager cManager =
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002769 (ConnectivityManager) mWebView
2770 .getContext().getSystemService(
2771 Context.CONNECTIVITY_SERVICE);
2772 NetworkInfo nInfo = cManager
2773 .getActiveNetworkInfo();
2774 if (nInfo != null) {
2775 performanceString = performanceString
2776 + "\nNetwork Type: "
2777 + nInfo.getType().toString();
2778 }
2779 }
2780 Checkin.logEvent(mResolver,
2781 Checkin.Events.Tag.WEBPAGE_LOAD,
2782 performanceString);
2783 Log.w(LOGTAG, "pushed to the statistics service");
2784 }
2785 */
2786 }
2787 }
2788 }
2789
2790 if (mInTrace) {
2791 mInTrace = false;
2792 Debug.stopMethodTracing();
2793 }
2794
2795 if (mPageStarted) {
2796 mPageStarted = false;
2797 // pauseWebView() will do nothing and return false if onPause()
2798 // is not called yet.
2799 if (pauseWebView()) {
2800 if (mWakeLock.isHeld()) {
2801 mHandler.removeMessages(RELEASE_WAKELOCK);
2802 mWakeLock.release();
2803 }
2804 }
2805 }
2806
2807 if (mInLoad) {
2808 mInLoad = false;
2809 updateInLoadMenuItems();
2810 }
2811
2812 mHandler.removeMessages(CHECK_MEMORY);
2813 checkMemory();
2814 }
2815
2816 // return true if want to hijack the url to let another app to handle it
2817 @Override
2818 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2819 if (url.startsWith(SCHEME_WTAI)) {
2820 // wtai://wp/mc;number
2821 // number=string(phone-number)
2822 if (url.startsWith(SCHEME_WTAI_MC)) {
2823 Intent intent = new Intent(Intent.ACTION_VIEW,
2824 Uri.parse(WebView.SCHEME_TEL +
2825 url.substring(SCHEME_WTAI_MC.length())));
2826 startActivity(intent);
2827 return true;
2828 }
2829 // wtai://wp/sd;dtmf
2830 // dtmf=string(dialstring)
2831 if (url.startsWith(SCHEME_WTAI_SD)) {
2832 // TODO
2833 // only send when there is active voice connection
2834 return false;
2835 }
2836 // wtai://wp/ap;number;name
2837 // number=string(phone-number)
2838 // name=string
2839 if (url.startsWith(SCHEME_WTAI_AP)) {
2840 // TODO
2841 return false;
2842 }
2843 }
2844
2845 Uri uri;
2846 try {
2847 uri = Uri.parse(url);
2848 } catch (IllegalArgumentException ex) {
2849 return false;
2850 }
2851
2852 // check whether other activities want to handle this url
2853 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
2854 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2855 try {
2856 if (startActivityIfNeeded(intent, -1)) {
2857 return true;
2858 }
2859 } catch (ActivityNotFoundException ex) {
2860 // ignore the error. If no application can handle the URL,
2861 // eg about:blank, assume the browser can handle it.
2862 }
2863
2864 if (mMenuIsDown) {
2865 openTab(url);
2866 closeOptionsMenu();
2867 return true;
2868 }
2869
2870 return false;
2871 }
2872
2873 /**
2874 * Updates the lock icon. This method is called when we discover another
2875 * resource to be loaded for this page (for example, javascript). While
2876 * we update the icon type, we do not update the lock icon itself until
2877 * we are done loading, it is slightly more secure this way.
2878 */
2879 @Override
2880 public void onLoadResource(WebView view, String url) {
2881 if (url != null && url.length() > 0) {
2882 // It is only if the page claims to be secure
2883 // that we may have to update the lock:
2884 if (mLockIconType == LOCK_ICON_SECURE) {
2885 // If NOT a 'safe' url, change the lock to mixed content!
2886 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2887 mLockIconType = LOCK_ICON_MIXED;
2888 if (Config.LOGV) {
2889 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2890 " updated lock icon to " + mLockIconType + " due to " + url);
2891 }
2892 }
2893 }
2894 }
2895 }
2896
2897 /**
2898 * Show the dialog, asking the user if they would like to continue after
2899 * an excessive number of HTTP redirects.
2900 */
2901 @Override
2902 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2903 final Message continueMsg) {
2904 new AlertDialog.Builder(BrowserActivity.this)
2905 .setTitle(R.string.browserFrameRedirect)
2906 .setMessage(R.string.browserFrame307Post)
2907 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2908 public void onClick(DialogInterface dialog, int which) {
2909 continueMsg.sendToTarget();
2910 }})
2911 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2912 public void onClick(DialogInterface dialog, int which) {
2913 cancelMsg.sendToTarget();
2914 }})
2915 .setOnCancelListener(new OnCancelListener() {
2916 public void onCancel(DialogInterface dialog) {
2917 cancelMsg.sendToTarget();
2918 }})
2919 .show();
2920 }
2921
2922 /**
2923 * Show a dialog informing the user of the network error reported by
2924 * WebCore.
2925 */
2926 @Override
2927 public void onReceivedError(WebView view, int errorCode,
2928 String description, String failingUrl) {
2929 if (errorCode != EventHandler.ERROR_LOOKUP &&
2930 errorCode != EventHandler.ERROR_CONNECT &&
2931 errorCode != EventHandler.ERROR_BAD_URL &&
The Android Open Source Projected217d92008-12-17 18:05:52 -08002932 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07002933 errorCode != EventHandler.FILE_ERROR) {
2934 new AlertDialog.Builder(BrowserActivity.this)
2935 .setTitle((errorCode == EventHandler.FILE_NOT_FOUND_ERROR) ?
2936 R.string.browserFrameFileErrorLabel :
2937 R.string.browserFrameNetworkErrorLabel)
2938 .setMessage(description)
2939 .setPositiveButton(R.string.ok, null)
2940 .show();
2941 }
2942 Log.e(LOGTAG, "onReceivedError code:"+errorCode+" "+description);
2943
2944 // We need to reset the title after an error.
2945 resetTitleAndRevertLockIcon();
2946 }
2947
2948 /**
2949 * Check with the user if it is ok to resend POST data as the page they
2950 * are trying to navigate to is the result of a POST.
2951 */
2952 @Override
2953 public void onFormResubmission(WebView view, final Message dontResend,
2954 final Message resend) {
2955 new AlertDialog.Builder(BrowserActivity.this)
2956 .setTitle(R.string.browserFrameFormResubmitLabel)
2957 .setMessage(R.string.browserFrameFormResubmitMessage)
2958 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2959 public void onClick(DialogInterface dialog, int which) {
2960 resend.sendToTarget();
2961 }})
2962 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2963 public void onClick(DialogInterface dialog, int which) {
2964 dontResend.sendToTarget();
2965 }})
2966 .setOnCancelListener(new OnCancelListener() {
2967 public void onCancel(DialogInterface dialog) {
2968 dontResend.sendToTarget();
2969 }})
2970 .show();
2971 }
2972
2973 /**
2974 * Insert the url into the visited history database.
2975 * @param url The url to be inserted.
2976 * @param isReload True if this url is being reloaded.
2977 * FIXME: Not sure what to do when reloading the page.
2978 */
2979 @Override
2980 public void doUpdateVisitedHistory(WebView view, String url,
2981 boolean isReload) {
2982 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2983 return;
2984 }
2985 Browser.updateVisitedHistory(mResolver, url, true);
2986 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2987 }
2988
2989 /**
2990 * Displays SSL error(s) dialog to the user.
2991 */
2992 @Override
2993 public void onReceivedSslError(
2994 final WebView view, final SslErrorHandler handler, final SslError error) {
2995
2996 if (mSettings.showSecurityWarnings()) {
2997 final LayoutInflater factory =
2998 LayoutInflater.from(BrowserActivity.this);
2999 final View warningsView =
3000 factory.inflate(R.layout.ssl_warnings, null);
3001 final LinearLayout placeholder =
3002 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3003
3004 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3005 LinearLayout ll = (LinearLayout)factory
3006 .inflate(R.layout.ssl_warning, null);
3007 ((TextView)ll.findViewById(R.id.warning))
3008 .setText(R.string.ssl_untrusted);
3009 placeholder.addView(ll);
3010 }
3011
3012 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3013 LinearLayout ll = (LinearLayout)factory
3014 .inflate(R.layout.ssl_warning, null);
3015 ((TextView)ll.findViewById(R.id.warning))
3016 .setText(R.string.ssl_mismatch);
3017 placeholder.addView(ll);
3018 }
3019
3020 if (error.hasError(SslError.SSL_EXPIRED)) {
3021 LinearLayout ll = (LinearLayout)factory
3022 .inflate(R.layout.ssl_warning, null);
3023 ((TextView)ll.findViewById(R.id.warning))
3024 .setText(R.string.ssl_expired);
3025 placeholder.addView(ll);
3026 }
3027
3028 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3029 LinearLayout ll = (LinearLayout)factory
3030 .inflate(R.layout.ssl_warning, null);
3031 ((TextView)ll.findViewById(R.id.warning))
3032 .setText(R.string.ssl_not_yet_valid);
3033 placeholder.addView(ll);
3034 }
3035
3036 new AlertDialog.Builder(BrowserActivity.this)
3037 .setTitle(R.string.security_warning)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003038 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003039 .setView(warningsView)
3040 .setPositiveButton(R.string.ssl_continue,
3041 new DialogInterface.OnClickListener() {
3042 public void onClick(DialogInterface dialog, int whichButton) {
3043 handler.proceed();
3044 }
3045 })
3046 .setNeutralButton(R.string.view_certificate,
3047 new DialogInterface.OnClickListener() {
3048 public void onClick(DialogInterface dialog, int whichButton) {
3049 showSSLCertificateOnError(view, handler, error);
3050 }
3051 })
3052 .setNegativeButton(R.string.cancel,
3053 new DialogInterface.OnClickListener() {
3054 public void onClick(DialogInterface dialog, int whichButton) {
3055 handler.cancel();
3056 BrowserActivity.this.resetTitleAndRevertLockIcon();
3057 }
3058 })
3059 .setOnCancelListener(
3060 new DialogInterface.OnCancelListener() {
3061 public void onCancel(DialogInterface dialog) {
3062 handler.cancel();
3063 BrowserActivity.this.resetTitleAndRevertLockIcon();
3064 }
3065 })
3066 .show();
3067 } else {
3068 handler.proceed();
3069 }
3070 }
3071
3072 /**
3073 * Handles an HTTP authentication request.
3074 *
3075 * @param handler The authentication handler
3076 * @param host The host
3077 * @param realm The realm
3078 */
3079 @Override
3080 public void onReceivedHttpAuthRequest(WebView view,
3081 final HttpAuthHandler handler, final String host, final String realm) {
3082 String username = null;
3083 String password = null;
3084
3085 boolean reuseHttpAuthUsernamePassword =
3086 handler.useHttpAuthUsernamePassword();
3087
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003088 if (reuseHttpAuthUsernamePassword &&
3089 (mTabControl.getCurrentWebView() != null)) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003090 String[] credentials =
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003091 mTabControl.getCurrentWebView()
3092 .getHttpAuthUsernamePassword(host, realm);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003093 if (credentials != null && credentials.length == 2) {
3094 username = credentials[0];
3095 password = credentials[1];
3096 }
3097 }
3098
3099 if (username != null && password != null) {
3100 handler.proceed(username, password);
3101 } else {
3102 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3103 }
3104 }
3105
3106 @Override
3107 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3108 if (mMenuIsDown) {
3109 // only check shortcut key when MENU is held
3110 return getWindow().isShortcutKey(event.getKeyCode(), event);
3111 } else {
3112 return false;
3113 }
3114 }
3115
3116 @Override
3117 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003118 if (view != mTabControl.getCurrentTopWebView()) {
3119 return;
3120 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003121 if (event.isDown()) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003122 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003123 } else {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003124 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003125 }
3126 }
3127 };
3128
3129 //--------------------------------------------------------------------------
3130 // WebChromeClient implementation
3131 //--------------------------------------------------------------------------
3132
3133 /* package */ WebChromeClient getWebChromeClient() {
3134 return mWebChromeClient;
3135 }
3136
3137 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3138 // Helper method to create a new tab or sub window.
3139 private void createWindow(final boolean dialog, final Message msg) {
3140 if (dialog) {
3141 mTabControl.createSubWindow();
3142 final TabControl.Tab t = mTabControl.getCurrentTab();
3143 attachSubWindow(t);
The Android Open Source Project066e9082009-01-20 14:03:59 -08003144 WebView.WebViewTransport transport =
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003145 (WebView.WebViewTransport) msg.obj;
3146 transport.setWebView(t.getSubWebView());
3147 msg.sendToTarget();
3148 } else {
3149 final TabControl.Tab parent = mTabControl.getCurrentTab();
3150 // openTabAndShow will dispatch the message after creating the
3151 // new WebView. This will prevent another request from coming
3152 // in during the animation.
The Android Open Source Projected217d92008-12-17 18:05:52 -08003153 openTabAndShow(null, msg, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003154 parent.addChildTab(mTabControl.getCurrentTab());
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003155 WebView.WebViewTransport transport =
3156 (WebView.WebViewTransport) msg.obj;
3157 transport.setWebView(mTabControl.getCurrentWebView());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003158 }
3159 }
3160
3161 @Override
3162 public boolean onCreateWindow(WebView view, final boolean dialog,
3163 final boolean userGesture, final Message resultMsg) {
3164 // Ignore these requests during tab animations or if the tab
3165 // overview is showing.
3166 if (mAnimationCount > 0 || mTabOverview != null) {
3167 return false;
3168 }
3169 // Short-circuit if we can't create any more tabs or sub windows.
3170 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3171 new AlertDialog.Builder(BrowserActivity.this)
3172 .setTitle(R.string.too_many_subwindows_dialog_title)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003173 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003174 .setMessage(R.string.too_many_subwindows_dialog_message)
3175 .setPositiveButton(R.string.ok, null)
3176 .show();
3177 return false;
3178 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3179 new AlertDialog.Builder(BrowserActivity.this)
3180 .setTitle(R.string.too_many_windows_dialog_title)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003181 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003182 .setMessage(R.string.too_many_windows_dialog_message)
3183 .setPositiveButton(R.string.ok, null)
3184 .show();
3185 return false;
3186 }
3187
3188 // Short-circuit if this was a user gesture.
3189 if (userGesture) {
3190 // createWindow will call openTabAndShow for new Windows and
3191 // that will call tabPicker which will increment
3192 // mAnimationCount.
3193 createWindow(dialog, resultMsg);
3194 return true;
3195 }
3196
3197 // Allow the popup and create the appropriate window.
3198 final AlertDialog.OnClickListener allowListener =
3199 new AlertDialog.OnClickListener() {
3200 public void onClick(DialogInterface d,
3201 int which) {
3202 // Same comment as above for setting
3203 // mAnimationCount.
3204 createWindow(dialog, resultMsg);
3205 // Since we incremented mAnimationCount while the
3206 // dialog was up, we have to decrement it here.
3207 mAnimationCount--;
3208 }
3209 };
3210
3211 // Block the popup by returning a null WebView.
3212 final AlertDialog.OnClickListener blockListener =
3213 new AlertDialog.OnClickListener() {
3214 public void onClick(DialogInterface d, int which) {
3215 resultMsg.sendToTarget();
3216 // We are not going to trigger an animation so
3217 // unblock keys and animation requests.
3218 mAnimationCount--;
3219 }
3220 };
3221
3222 // Build a confirmation dialog to display to the user.
3223 final AlertDialog d =
3224 new AlertDialog.Builder(BrowserActivity.this)
3225 .setTitle(R.string.attention)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003226 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003227 .setMessage(R.string.popup_window_attempt)
3228 .setPositiveButton(R.string.allow, allowListener)
3229 .setNegativeButton(R.string.block, blockListener)
3230 .setCancelable(false)
3231 .create();
3232
3233 // Show the confirmation dialog.
3234 d.show();
3235 // We want to increment mAnimationCount here to prevent a
3236 // potential race condition. If the user allows a pop-up from a
3237 // site and that pop-up then triggers another pop-up, it is
3238 // possible to get the BACK key between here and when the dialog
3239 // appears.
3240 mAnimationCount++;
3241 return true;
3242 }
3243
3244 @Override
3245 public void onCloseWindow(WebView window) {
3246 final int currentIndex = mTabControl.getCurrentIndex();
3247 final TabControl.Tab parent =
3248 mTabControl.getCurrentTab().getParentTab();
3249 if (parent != null) {
3250 // JavaScript can only close popup window.
The Android Open Source Projected217d92008-12-17 18:05:52 -08003251 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003252 }
3253 }
3254
3255 @Override
3256 public void onProgressChanged(WebView view, int newProgress) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003257 // Block progress updates to the title bar while the tab overview
3258 // is animating or being displayed.
3259 if (mAnimationCount == 0 && mTabOverview == null) {
3260 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3261 newProgress * 100);
3262 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003263
3264 if (newProgress == 100) {
3265 // onProgressChanged() is called for sub-frame too while
3266 // onPageFinished() is only called for the main frame. sync
3267 // cookie and cache promptly here.
3268 CookieSyncManager.getInstance().sync();
3269 }
3270 }
3271
3272 @Override
3273 public void onReceivedTitle(WebView view, String title) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003274 String url = view.getOriginalUrl();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003275
3276 // here, if url is null, we want to reset the title
3277 setUrlTitle(url, title);
3278
3279 if (url == null ||
3280 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3281 return;
3282 }
3283 if (url.startsWith("http://www.")) {
3284 url = url.substring(11);
3285 } else if (url.startsWith("http://")) {
3286 url = url.substring(4);
3287 }
3288 try {
3289 url = "%" + url;
3290 String [] selArgs = new String[] { url };
The Android Open Source Project066e9082009-01-20 14:03:59 -08003291
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003292 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3293 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3294 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3295 Browser.HISTORY_PROJECTION, where, selArgs, null);
3296 if (c.moveToFirst()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003297 if (Config.LOGV) {
3298 Log.v(LOGTAG, "updating cursor");
3299 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003300 // Current implementation of database only has one entry per
3301 // url.
3302 int titleIndex =
3303 c.getColumnIndex(Browser.BookmarkColumns.TITLE);
3304 c.updateString(titleIndex, title);
3305 c.commitUpdates();
3306 }
3307 c.close();
3308 } catch (IllegalStateException e) {
3309 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3310 } catch (SQLiteException ex) {
3311 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3312 }
3313 }
3314
3315 @Override
3316 public void onReceivedIcon(WebView view, Bitmap icon) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003317 updateIcon(view.getUrl(), icon);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003318 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003319 };
3320
3321 /**
3322 * Notify the host application a download should be done, or that
3323 * the data should be streamed if a streaming viewer is available.
3324 * @param url The full url to the content that should be downloaded
3325 * @param contentDisposition Content-disposition http header, if
3326 * present.
3327 * @param mimetype The mimetype of the content reported by the server
3328 * @param contentLength The file size reported by the server
3329 */
3330 public void onDownloadStart(String url, String userAgent,
3331 String contentDisposition, String mimetype, long contentLength) {
3332 // if we're dealing wih A/V content that's not explicitly marked
3333 // for download, check if it's streamable.
3334 if (contentDisposition == null
3335 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3336 // query the package manager to see if there's a registered handler
3337 // that matches.
3338 Intent intent = new Intent(Intent.ACTION_VIEW);
3339 intent.setDataAndType(Uri.parse(url), mimetype);
3340 if (getPackageManager().queryIntentActivities(intent,
3341 PackageManager.MATCH_DEFAULT_ONLY).size() != 0) {
3342 // someone knows how to handle this mime type with this scheme, don't download.
3343 try {
3344 startActivity(intent);
3345 return;
3346 } catch (ActivityNotFoundException ex) {
3347 if (Config.LOGD) {
3348 Log.d(LOGTAG, "activity not found for " + mimetype
3349 + " over " + Uri.parse(url).getScheme(), ex);
3350 }
3351 // Best behavior is to fall back to a download in this case
3352 }
3353 }
3354 }
3355 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3356 }
3357
3358 /**
3359 * Notify the host application a download should be done, even if there
3360 * is a streaming viewer available for thise type.
3361 * @param url The full url to the content that should be downloaded
3362 * @param contentDisposition Content-disposition http header, if
3363 * present.
3364 * @param mimetype The mimetype of the content reported by the server
3365 * @param contentLength The file size reported by the server
3366 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08003367 /*package */ void onDownloadStartNoStream(String url, String userAgent,
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003368 String contentDisposition, String mimetype, long contentLength) {
3369
3370 String filename = URLUtil.guessFileName(url,
3371 contentDisposition, mimetype);
3372
3373 // Check to see if we have an SDCard
The Android Open Source Projected217d92008-12-17 18:05:52 -08003374 String status = Environment.getExternalStorageState();
3375 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3376 int title;
3377 String msg;
3378
3379 // Check to see if the SDCard is busy, same as the music app
3380 if (status.equals(Environment.MEDIA_SHARED)) {
3381 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3382 title = R.string.download_sdcard_busy_dlg_title;
3383 } else {
3384 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3385 title = R.string.download_no_sdcard_dlg_title;
3386 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003387
3388 new AlertDialog.Builder(this)
The Android Open Source Projected217d92008-12-17 18:05:52 -08003389 .setTitle(title)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003390 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003391 .setMessage(msg)
3392 .setPositiveButton(R.string.ok, null)
3393 .show();
3394 return;
3395 }
3396
The Android Open Source Projectfbb2a3a2009-02-13 12:57:52 -08003397 // java.net.URI is a lot stricter than KURL so we have to undo
3398 // KURL's percent-encoding and redo the encoding using java.net.URI.
3399 URI uri = null;
3400 try {
3401 // Undo the percent-encoding that KURL may have done.
3402 String newUrl = new String(URLUtil.decode(url.getBytes()));
3403 // Parse the url into pieces
3404 WebAddress w = new WebAddress(newUrl);
3405 String frag = null;
3406 String query = null;
3407 String path = w.mPath;
3408 // Break the path into path, query, and fragment
3409 if (path.length() > 0) {
3410 // Strip the fragment
3411 int idx = path.lastIndexOf('#');
3412 if (idx != -1) {
3413 frag = path.substring(idx + 1);
3414 path = path.substring(0, idx);
3415 }
3416 idx = path.lastIndexOf('?');
3417 if (idx != -1) {
3418 query = path.substring(idx + 1);
3419 path = path.substring(0, idx);
3420 }
3421 }
3422 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3423 query, frag);
3424 } catch (Exception e) {
3425 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3426 return;
3427 }
3428
3429 // XXX: Have to use the old url since the cookies were stored using the
3430 // old percent-encoded url.
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003431 String cookies = CookieManager.getInstance().getCookie(url);
3432
3433 ContentValues values = new ContentValues();
The Android Open Source Projectfbb2a3a2009-02-13 12:57:52 -08003434 values.put(Downloads.URI, uri.toString());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003435 values.put(Downloads.COOKIE_DATA, cookies);
3436 values.put(Downloads.USER_AGENT, userAgent);
3437 values.put(Downloads.NOTIFICATION_PACKAGE,
3438 getPackageName());
3439 values.put(Downloads.NOTIFICATION_CLASS,
3440 BrowserDownloadPage.class.getCanonicalName());
3441 values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3442 values.put(Downloads.MIMETYPE, mimetype);
3443 values.put(Downloads.FILENAME_HINT, filename);
The Android Open Source Projectfbb2a3a2009-02-13 12:57:52 -08003444 values.put(Downloads.DESCRIPTION, uri.getHost());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003445 if (contentLength > 0) {
3446 values.put(Downloads.TOTAL_BYTES, contentLength);
3447 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08003448 if (mimetype == null) {
3449 // We must have long pressed on a link or image to download it. We
3450 // are not sure of the mimetype in this case, so do a head request
3451 new FetchUrlMimeType(this).execute(values);
3452 } else {
3453 final Uri contentUri =
3454 getContentResolver().insert(Downloads.CONTENT_URI, values);
3455 viewDownloads(contentUri);
3456 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003457
3458 }
3459
3460 /**
3461 * Resets the lock icon. This method is called when we start a new load and
3462 * know the url to be loaded.
3463 */
3464 private void resetLockIcon(String url) {
3465 // Save the lock-icon state (we revert to it if the load gets cancelled)
3466 saveLockIcon();
3467
3468 mLockIconType = LOCK_ICON_UNSECURE;
3469 if (URLUtil.isHttpsUrl(url)) {
3470 mLockIconType = LOCK_ICON_SECURE;
3471 if (Config.LOGV) {
3472 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3473 " reset lock icon to " + mLockIconType);
3474 }
3475 }
3476
3477 updateLockIconImage(LOCK_ICON_UNSECURE);
3478 }
3479
3480 /**
3481 * Resets the lock icon. This method is called when the icon needs to be
3482 * reset but we do not know whether we are loading a secure or not secure
3483 * page.
3484 */
3485 private void resetLockIcon() {
3486 // Save the lock-icon state (we revert to it if the load gets cancelled)
3487 saveLockIcon();
3488
3489 mLockIconType = LOCK_ICON_UNSECURE;
3490
3491 if (Config.LOGV) {
3492 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3493 " reset lock icon to " + mLockIconType);
3494 }
3495
3496 updateLockIconImage(LOCK_ICON_UNSECURE);
3497 }
3498
3499 /**
3500 * Updates the lock-icon image in the title-bar.
3501 */
3502 private void updateLockIconImage(int lockIconType) {
3503 Drawable d = null;
3504 if (lockIconType == LOCK_ICON_SECURE) {
3505 d = mSecLockIcon;
3506 } else if (lockIconType == LOCK_ICON_MIXED) {
3507 d = mMixLockIcon;
3508 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08003509 // If the tab overview is animating or being shown, do not update the
3510 // lock icon.
3511 if (mAnimationCount == 0 && mTabOverview == null) {
3512 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
3513 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003514 }
3515
3516 /**
3517 * Displays a page-info dialog.
The Android Open Source Projected217d92008-12-17 18:05:52 -08003518 * @param tab The tab to show info about
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003519 * @param fromShowSSLCertificateOnError The flag that indicates whether
3520 * this dialog was opened from the SSL-certificate-on-error dialog or
3521 * not. This is important, since we need to know whether to return to
3522 * the parent dialog or simply dismiss.
3523 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08003524 private void showPageInfo(final TabControl.Tab tab,
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003525 final boolean fromShowSSLCertificateOnError) {
3526 final LayoutInflater factory = LayoutInflater
3527 .from(this);
3528
3529 final View pageInfoView = factory.inflate(R.layout.page_info, null);
The Android Open Source Project066e9082009-01-20 14:03:59 -08003530
The Android Open Source Projected217d92008-12-17 18:05:52 -08003531 final WebView view = tab.getWebView();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003532
3533 String url = null;
3534 String title = null;
3535
The Android Open Source Projected217d92008-12-17 18:05:52 -08003536 if (view == null) {
3537 url = tab.getUrl();
3538 title = tab.getTitle();
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003539 } else if (view == mTabControl.getCurrentWebView()) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003540 // Use the cached title and url if this is the current WebView
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003541 url = mUrl;
3542 title = mTitle;
3543 } else {
3544 url = view.getUrl();
3545 title = view.getTitle();
3546 }
3547
3548 if (url == null) {
3549 url = "";
3550 }
3551 if (title == null) {
3552 title = "";
3553 }
3554
3555 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3556 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3557
The Android Open Source Projected217d92008-12-17 18:05:52 -08003558 mPageInfoView = tab;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003559 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3560
3561 AlertDialog.Builder alertDialogBuilder =
3562 new AlertDialog.Builder(this)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003563 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003564 .setView(pageInfoView)
3565 .setPositiveButton(
3566 R.string.ok,
3567 new DialogInterface.OnClickListener() {
3568 public void onClick(DialogInterface dialog,
3569 int whichButton) {
3570 mPageInfoDialog = null;
3571 mPageInfoView = null;
3572 mPageInfoFromShowSSLCertificateOnError = null;
3573
3574 // if we came here from the SSL error dialog
3575 if (fromShowSSLCertificateOnError) {
3576 // go back to the SSL error dialog
3577 showSSLCertificateOnError(
3578 mSSLCertificateOnErrorView,
3579 mSSLCertificateOnErrorHandler,
3580 mSSLCertificateOnErrorError);
3581 }
3582 }
3583 })
3584 .setOnCancelListener(
3585 new DialogInterface.OnCancelListener() {
3586 public void onCancel(DialogInterface dialog) {
3587 mPageInfoDialog = null;
3588 mPageInfoView = null;
3589 mPageInfoFromShowSSLCertificateOnError = null;
3590
3591 // if we came here from the SSL error dialog
3592 if (fromShowSSLCertificateOnError) {
3593 // go back to the SSL error dialog
3594 showSSLCertificateOnError(
3595 mSSLCertificateOnErrorView,
3596 mSSLCertificateOnErrorHandler,
3597 mSSLCertificateOnErrorError);
3598 }
3599 }
3600 });
3601
3602 // if we have a main top-level page SSL certificate set or a certificate
3603 // error
The Android Open Source Project066e9082009-01-20 14:03:59 -08003604 if (fromShowSSLCertificateOnError ||
The Android Open Source Projected217d92008-12-17 18:05:52 -08003605 (view != null && view.getCertificate() != null)) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003606 // add a 'View Certificate' button
3607 alertDialogBuilder.setNeutralButton(
3608 R.string.view_certificate,
3609 new DialogInterface.OnClickListener() {
3610 public void onClick(DialogInterface dialog,
3611 int whichButton) {
3612 mPageInfoDialog = null;
3613 mPageInfoView = null;
3614 mPageInfoFromShowSSLCertificateOnError = null;
3615
3616 // if we came here from the SSL error dialog
3617 if (fromShowSSLCertificateOnError) {
3618 // go back to the SSL error dialog
3619 showSSLCertificateOnError(
3620 mSSLCertificateOnErrorView,
3621 mSSLCertificateOnErrorHandler,
3622 mSSLCertificateOnErrorError);
3623 } else {
3624 // otherwise, display the top-most certificate from
3625 // the chain
3626 if (view.getCertificate() != null) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08003627 showSSLCertificate(tab);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003628 }
3629 }
3630 }
3631 });
3632 }
3633
3634 mPageInfoDialog = alertDialogBuilder.show();
3635 }
3636
3637 /**
3638 * Displays the main top-level page SSL certificate dialog
3639 * (accessible from the Page-Info dialog).
The Android Open Source Projected217d92008-12-17 18:05:52 -08003640 * @param tab The tab to show certificate for.
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003641 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08003642 private void showSSLCertificate(final TabControl.Tab tab) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003643 final View certificateView =
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003644 inflateCertificateView(tab.getWebView().getCertificate());
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003645 if (certificateView == null) {
3646 return;
3647 }
3648
3649 LayoutInflater factory = LayoutInflater.from(this);
3650
3651 final LinearLayout placeholder =
3652 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3653
3654 LinearLayout ll = (LinearLayout) factory.inflate(
3655 R.layout.ssl_success, placeholder);
3656 ((TextView)ll.findViewById(R.id.success))
3657 .setText(R.string.ssl_certificate_is_valid);
3658
The Android Open Source Projected217d92008-12-17 18:05:52 -08003659 mSSLCertificateView = tab;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003660 mSSLCertificateDialog =
3661 new AlertDialog.Builder(this)
3662 .setTitle(R.string.ssl_certificate).setIcon(
3663 R.drawable.ic_dialog_browser_certificate_secure)
3664 .setView(certificateView)
3665 .setPositiveButton(R.string.ok,
3666 new DialogInterface.OnClickListener() {
3667 public void onClick(DialogInterface dialog,
3668 int whichButton) {
3669 mSSLCertificateDialog = null;
3670 mSSLCertificateView = null;
3671
The Android Open Source Projected217d92008-12-17 18:05:52 -08003672 showPageInfo(tab, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003673 }
3674 })
3675 .setOnCancelListener(
3676 new DialogInterface.OnCancelListener() {
3677 public void onCancel(DialogInterface dialog) {
3678 mSSLCertificateDialog = null;
3679 mSSLCertificateView = null;
3680
The Android Open Source Projected217d92008-12-17 18:05:52 -08003681 showPageInfo(tab, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003682 }
3683 })
3684 .show();
3685 }
3686
3687 /**
3688 * Displays the SSL error certificate dialog.
3689 * @param view The target web-view.
3690 * @param handler The SSL error handler responsible for cancelling the
3691 * connection that resulted in an SSL error or proceeding per user request.
3692 * @param error The SSL error object.
3693 */
3694 private void showSSLCertificateOnError(
3695 final WebView view, final SslErrorHandler handler, final SslError error) {
3696
3697 final View certificateView =
3698 inflateCertificateView(error.getCertificate());
3699 if (certificateView == null) {
3700 return;
3701 }
3702
3703 LayoutInflater factory = LayoutInflater.from(this);
3704
3705 final LinearLayout placeholder =
3706 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3707
3708 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3709 LinearLayout ll = (LinearLayout)factory
3710 .inflate(R.layout.ssl_warning, placeholder);
3711 ((TextView)ll.findViewById(R.id.warning))
3712 .setText(R.string.ssl_untrusted);
3713 }
3714
3715 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3716 LinearLayout ll = (LinearLayout)factory
3717 .inflate(R.layout.ssl_warning, placeholder);
3718 ((TextView)ll.findViewById(R.id.warning))
3719 .setText(R.string.ssl_mismatch);
3720 }
3721
3722 if (error.hasError(SslError.SSL_EXPIRED)) {
3723 LinearLayout ll = (LinearLayout)factory
3724 .inflate(R.layout.ssl_warning, placeholder);
3725 ((TextView)ll.findViewById(R.id.warning))
3726 .setText(R.string.ssl_expired);
3727 }
3728
3729 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3730 LinearLayout ll = (LinearLayout)factory
3731 .inflate(R.layout.ssl_warning, placeholder);
3732 ((TextView)ll.findViewById(R.id.warning))
3733 .setText(R.string.ssl_not_yet_valid);
3734 }
3735
3736 mSSLCertificateOnErrorHandler = handler;
3737 mSSLCertificateOnErrorView = view;
3738 mSSLCertificateOnErrorError = error;
3739 mSSLCertificateOnErrorDialog =
3740 new AlertDialog.Builder(this)
3741 .setTitle(R.string.ssl_certificate).setIcon(
3742 R.drawable.ic_dialog_browser_certificate_partially_secure)
3743 .setView(certificateView)
3744 .setPositiveButton(R.string.ok,
3745 new DialogInterface.OnClickListener() {
3746 public void onClick(DialogInterface dialog,
3747 int whichButton) {
3748 mSSLCertificateOnErrorDialog = null;
3749 mSSLCertificateOnErrorView = null;
3750 mSSLCertificateOnErrorHandler = null;
3751 mSSLCertificateOnErrorError = null;
3752
3753 mWebViewClient.onReceivedSslError(
3754 view, handler, error);
3755 }
3756 })
3757 .setNeutralButton(R.string.page_info_view,
3758 new DialogInterface.OnClickListener() {
3759 public void onClick(DialogInterface dialog,
3760 int whichButton) {
3761 mSSLCertificateOnErrorDialog = null;
3762
3763 // do not clear the dialog state: we will
3764 // need to show the dialog again once the
3765 // user is done exploring the page-info details
3766
The Android Open Source Project066e9082009-01-20 14:03:59 -08003767 showPageInfo(mTabControl.getTabFromView(view),
The Android Open Source Projected217d92008-12-17 18:05:52 -08003768 true);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003769 }
3770 })
3771 .setOnCancelListener(
3772 new DialogInterface.OnCancelListener() {
3773 public void onCancel(DialogInterface dialog) {
3774 mSSLCertificateOnErrorDialog = null;
3775 mSSLCertificateOnErrorView = null;
3776 mSSLCertificateOnErrorHandler = null;
3777 mSSLCertificateOnErrorError = null;
3778
3779 mWebViewClient.onReceivedSslError(
3780 view, handler, error);
3781 }
3782 })
3783 .show();
3784 }
3785
3786 /**
3787 * Inflates the SSL certificate view (helper method).
3788 * @param certificate The SSL certificate.
3789 * @return The resultant certificate view with issued-to, issued-by,
3790 * issued-on, expires-on, and possibly other fields set.
3791 * If the input certificate is null, returns null.
3792 */
3793 private View inflateCertificateView(SslCertificate certificate) {
3794 if (certificate == null) {
3795 return null;
3796 }
3797
3798 LayoutInflater factory = LayoutInflater.from(this);
3799
3800 View certificateView = factory.inflate(
3801 R.layout.ssl_certificate, null);
3802
3803 // issued to:
3804 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3805 if (issuedTo != null) {
3806 ((TextView) certificateView.findViewById(R.id.to_common))
3807 .setText(issuedTo.getCName());
3808 ((TextView) certificateView.findViewById(R.id.to_org))
3809 .setText(issuedTo.getOName());
3810 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3811 .setText(issuedTo.getUName());
3812 }
3813
3814 // issued by:
3815 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3816 if (issuedBy != null) {
3817 ((TextView) certificateView.findViewById(R.id.by_common))
3818 .setText(issuedBy.getCName());
3819 ((TextView) certificateView.findViewById(R.id.by_org))
3820 .setText(issuedBy.getOName());
3821 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3822 .setText(issuedBy.getUName());
3823 }
3824
3825 // issued on:
3826 String issuedOn = reformatCertificateDate(
3827 certificate.getValidNotBefore());
3828 ((TextView) certificateView.findViewById(R.id.issued_on))
3829 .setText(issuedOn);
3830
3831 // expires on:
3832 String expiresOn = reformatCertificateDate(
3833 certificate.getValidNotAfter());
3834 ((TextView) certificateView.findViewById(R.id.expires_on))
3835 .setText(expiresOn);
3836
3837 return certificateView;
3838 }
3839
3840 /**
3841 * Re-formats the certificate date (Date.toString()) string to
3842 * a properly localized date string.
3843 * @return Properly localized version of the certificate date string and
3844 * the original certificate date string if fails to localize.
3845 * If the original string is null, returns an empty string "".
3846 */
3847 private String reformatCertificateDate(String certificateDate) {
3848 String reformattedDate = null;
3849
3850 if (certificateDate != null) {
3851 Date date = null;
3852 try {
3853 date = java.text.DateFormat.getInstance().parse(certificateDate);
3854 } catch (ParseException e) {
3855 date = null;
3856 }
3857
3858 if (date != null) {
3859 reformattedDate =
3860 DateFormat.getDateFormat(this).format(date);
3861 }
3862 }
3863
3864 return reformattedDate != null ? reformattedDate :
3865 (certificateDate != null ? certificateDate : "");
3866 }
3867
3868 /**
3869 * Displays an http-authentication dialog.
3870 */
3871 private void showHttpAuthentication(final HttpAuthHandler handler,
3872 final String host, final String realm, final String title,
3873 final String name, final String password, int focusId) {
3874 LayoutInflater factory = LayoutInflater.from(this);
3875 final View v = factory
3876 .inflate(R.layout.http_authentication, null);
3877 if (name != null) {
3878 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3879 }
3880 if (password != null) {
3881 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3882 }
3883
3884 String titleText = title;
3885 if (titleText == null) {
3886 titleText = getText(R.string.sign_in_to).toString().replace(
3887 "%s1", host).replace("%s2", realm);
3888 }
3889
3890 mHttpAuthHandler = handler;
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08003891 AlertDialog dialog = new AlertDialog.Builder(this)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003892 .setTitle(titleText)
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003893 .setIcon(android.R.drawable.ic_dialog_alert)
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003894 .setView(v)
3895 .setPositiveButton(R.string.action,
3896 new DialogInterface.OnClickListener() {
3897 public void onClick(DialogInterface dialog,
3898 int whichButton) {
3899 String nm = ((EditText) v
3900 .findViewById(R.id.username_edit))
3901 .getText().toString();
3902 String pw = ((EditText) v
3903 .findViewById(R.id.password_edit))
3904 .getText().toString();
3905 BrowserActivity.this.setHttpAuthUsernamePassword
3906 (host, realm, nm, pw);
3907 handler.proceed(nm, pw);
3908 mHttpAuthenticationDialog = null;
3909 mHttpAuthHandler = null;
3910 }})
3911 .setNegativeButton(R.string.cancel,
3912 new DialogInterface.OnClickListener() {
3913 public void onClick(DialogInterface dialog,
3914 int whichButton) {
3915 handler.cancel();
3916 BrowserActivity.this.resetTitleAndRevertLockIcon();
3917 mHttpAuthenticationDialog = null;
3918 mHttpAuthHandler = null;
3919 }})
3920 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3921 public void onCancel(DialogInterface dialog) {
3922 handler.cancel();
3923 BrowserActivity.this.resetTitleAndRevertLockIcon();
3924 mHttpAuthenticationDialog = null;
3925 mHttpAuthHandler = null;
3926 }})
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08003927 .create();
3928 // Make the IME appear when the dialog is displayed if applicable.
3929 dialog.getWindow().setSoftInputMode(
3930 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3931 dialog.show();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003932 if (focusId != 0) {
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08003933 dialog.findViewById(focusId).requestFocus();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003934 } else {
3935 v.findViewById(R.id.username_edit).requestFocus();
3936 }
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08003937 mHttpAuthenticationDialog = dialog;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003938 }
3939
3940 public int getProgress() {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003941 WebView w = mTabControl.getCurrentWebView();
3942 if (w != null) {
3943 return w.getProgress();
3944 } else {
3945 return 100;
3946 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003947 }
3948
3949 /**
3950 * Set HTTP authentication password.
3951 *
3952 * @param host The host for the password
3953 * @param realm The realm for the password
3954 * @param username The username for the password. If it is null, it means
3955 * password can't be saved.
3956 * @param password The password
3957 */
3958 public void setHttpAuthUsernamePassword(String host, String realm,
3959 String username,
3960 String password) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003961 WebView w = mTabControl.getCurrentWebView();
3962 if (w != null) {
3963 w.setHttpAuthUsernamePassword(host, realm, username, password);
3964 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003965 }
3966
3967 /**
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08003968 * connectivity manager says net has come or gone... inform the user
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003969 * @param up true if net has come up, false if net has gone down
3970 */
3971 public void onNetworkToggle(boolean up) {
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08003972 if (up == mIsNetworkUp) {
3973 return;
3974 } else if (up) {
3975 mIsNetworkUp = true;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003976 if (mAlertDialog != null) {
3977 mAlertDialog.cancel();
3978 mAlertDialog = null;
3979 }
3980 } else {
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08003981 mIsNetworkUp = false;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003982 if (mInLoad && mAlertDialog == null) {
3983 mAlertDialog = new AlertDialog.Builder(this)
3984 .setTitle(R.string.loadSuspendedTitle)
3985 .setMessage(R.string.loadSuspended)
3986 .setPositiveButton(R.string.ok, null)
3987 .show();
3988 }
3989 }
The Android Open Source Project765e7c92009-01-09 17:51:25 -08003990 WebView w = mTabControl.getCurrentWebView();
3991 if (w != null) {
3992 w.setNetworkAvailable(up);
3993 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07003994 }
3995
3996 @Override
3997 protected void onActivityResult(int requestCode, int resultCode,
3998 Intent intent) {
3999 switch (requestCode) {
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08004000 case COMBO_PAGE:
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004001 if (resultCode == RESULT_OK && intent != null) {
4002 String data = intent.getAction();
4003 Bundle extras = intent.getExtras();
4004 if (extras != null && extras.getBoolean("new_window", false)) {
4005 openTab(data);
4006 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004007 final TabControl.Tab currentTab =
4008 mTabControl.getCurrentTab();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004009 // If the Window overview is up and we are not in the
4010 // middle of an animation, animate away from it to the
4011 // current tab.
4012 if (mTabOverview != null && mAnimationCount == 0) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004013 sendAnimateFromOverview(currentTab, false, data,
4014 TAB_OVERVIEW_DELAY, null);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004015 } else {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004016 dismissSubWindow(currentTab);
4017 if (data != null && data.length() != 0) {
4018 getTopWindow().loadUrl(data);
4019 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004020 }
4021 }
4022 }
4023 break;
4024 default:
4025 break;
4026 }
4027 getTopWindow().requestFocus();
4028 }
The Android Open Source Project066e9082009-01-20 14:03:59 -08004029
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004030 /*
4031 * This method is called as a result of the user selecting the options
4032 * menu to see the download window, or when a download changes state. It
4033 * shows the download window ontop of the current window.
4034 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08004035 /* package */ void viewDownloads(Uri downloadRecord) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004036 Intent intent = new Intent(this,
4037 BrowserDownloadPage.class);
4038 intent.setData(downloadRecord);
4039 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4040
4041 }
4042
4043 /**
4044 * Handle results from Tab Switcher mTabOverview tool
4045 */
4046 private class TabListener implements ImageGrid.Listener {
4047 public void remove(int position) {
4048 // Note: Remove is not enabled if we have only one tab.
4049 if (Config.DEBUG && mTabControl.getTabCount() == 1) {
4050 throw new AssertionError();
4051 }
4052
The Android Open Source Projected217d92008-12-17 18:05:52 -08004053 // Remember the current tab.
4054 TabControl.Tab current = mTabControl.getCurrentTab();
4055 final TabControl.Tab remove = mTabControl.getTab(position);
4056 mTabControl.removeTab(remove);
4057 // If we removed the current tab, use the tab at position - 1 if
4058 // possible.
4059 if (current == remove) {
4060 // If the user removes the last tab, act like the New Tab item
4061 // was clicked on.
4062 if (mTabControl.getTabCount() == 0) {
4063 current = mTabControl.createNewTab(false);
4064 sendAnimateFromOverview(current, true,
4065 mSettings.getHomePage(), TAB_OVERVIEW_DELAY, null);
4066 } else {
4067 final int index = position > 0 ? (position - 1) : 0;
4068 current = mTabControl.getTab(index);
4069 }
4070 }
4071
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004072 // The tab overview could have been dismissed before this method is
4073 // called.
4074 if (mTabOverview != null) {
4075 // Remove the tab and change the index.
The Android Open Source Projected217d92008-12-17 18:05:52 -08004076 mTabOverview.remove(position);
4077 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004078 }
4079
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004080 // Only the current tab ensures its WebView is non-null. This
4081 // implies that we are reloading the freed tab.
The Android Open Source Projected217d92008-12-17 18:05:52 -08004082 mTabControl.setCurrentTab(current);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004083 }
4084 public void onClick(int index) {
4085 // Change the tab if necessary.
4086 // Index equals ImageGrid.CANCEL when pressing back from the tab
4087 // overview.
4088 if (index == ImageGrid.CANCEL) {
4089 index = mTabControl.getCurrentIndex();
4090 // The current index is -1 if the current tab was removed.
4091 if (index == -1) {
4092 // Take the last tab as a fallback.
4093 index = mTabControl.getTabCount() - 1;
4094 }
4095 }
4096
4097 // Clear all the data for tab picker so next time it will be
4098 // recreated.
4099 mTabControl.wipeAllPickerData();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004100
4101 // NEW_TAB means that the "New Tab" cell was clicked on.
4102 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projected217d92008-12-17 18:05:52 -08004103 openTabAndShow(mSettings.getHomePage(), null, false);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004104 } else {
4105 sendAnimateFromOverview(mTabControl.getTab(index),
4106 false, null, 0, null);
4107 }
4108 }
4109 }
4110
4111 // A fake View that draws the WebView's picture with a fast zoom filter.
4112 // The View is used in case the tab is freed during the animation because
4113 // of low memory.
4114 private static class AnimatingView extends View {
4115 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4116 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4117 private static final DrawFilter sZoomFilter =
4118 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4119 private final Picture mPicture;
4120 private final float mScale;
4121 private final int mScrollX;
4122 private final int mScrollY;
4123 final TabControl.Tab mTab;
4124
4125 AnimatingView(Context ctxt, TabControl.Tab t) {
4126 super(ctxt);
4127 mTab = t;
4128 // Use the top window in the animation since the tab overview will
4129 // display the top window in each cell.
4130 final WebView w = t.getTopWindow();
4131 mPicture = w.capturePicture();
4132 mScale = w.getScale() / w.getWidth();
4133 mScrollX = w.getScrollX();
4134 mScrollY = w.getScrollY();
4135 }
4136
4137 @Override
4138 protected void onDraw(Canvas canvas) {
4139 canvas.save();
4140 canvas.drawColor(Color.WHITE);
The Android Open Source Projected217d92008-12-17 18:05:52 -08004141 if (mPicture != null) {
4142 canvas.setDrawFilter(sZoomFilter);
4143 float scale = getWidth() * mScale;
4144 canvas.scale(scale, scale);
4145 canvas.translate(-mScrollX, -mScrollY);
4146 canvas.drawPicture(mPicture);
4147 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004148 canvas.restore();
4149 }
4150 }
4151
4152 /**
4153 * Open the tab picker. This function will always use the current tab in
4154 * its animation.
4155 * @param stay boolean stating whether the tab picker is to remain open
4156 * (in which case it needs a listener and its menu) or not.
4157 * @param index The index of the tab to show as the selection in the tab
4158 * overview.
4159 * @param remove If true, the tab at index will be removed after the
4160 * animation completes.
4161 */
4162 private void tabPicker(final boolean stay, final int index,
4163 final boolean remove) {
4164 if (mTabOverview != null) {
4165 return;
4166 }
4167
4168 int size = mTabControl.getTabCount();
4169
4170 TabListener l = null;
4171 if (stay) {
4172 l = mTabListener = new TabListener();
4173 }
4174 mTabOverview = new ImageGrid(this, stay, l);
4175
4176 for (int i = 0; i < size; i++) {
4177 final TabControl.Tab t = mTabControl.getTab(i);
4178 mTabControl.populatePickerData(t);
4179 mTabOverview.add(t);
4180 }
4181
4182 // Tell the tab overview to show the current tab, the tab overview will
4183 // handle the "New Tab" case.
4184 int currentIndex = mTabControl.getCurrentIndex();
4185 mTabOverview.setCurrentIndex(currentIndex);
4186
4187 // Attach the tab overview.
4188 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4189
4190 // Create a fake AnimatingView to animate the WebView's picture.
4191 final TabControl.Tab current = mTabControl.getCurrentTab();
4192 final AnimatingView v = new AnimatingView(this, current);
4193 mContentView.addView(v, COVER_SCREEN_PARAMS);
4194 removeTabFromContentView(current);
4195 // Pause timers to get the animation smoother.
4196 current.getWebView().pauseTimers();
4197
4198 // Send a message so the tab picker has a chance to layout and get
4199 // positions for all the cells.
4200 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4201 index, remove ? 1 : 0, v));
4202 // Setting this will indicate that we are animating to the overview. We
4203 // set it here to prevent another request to animate from coming in
4204 // between now and when ANIMATE_TO_OVERVIEW is handled.
4205 mAnimationCount++;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004206 // Always change the title bar to the window overview title while
4207 // animating.
4208 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4209 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4210 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4211 Window.PROGRESS_VISIBILITY_OFF);
4212 setTitle(R.string.tab_picker_title);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004213 // Make the menu empty until the animation completes.
4214 mMenuState = EMPTY_MENU;
4215 }
4216
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08004217 private void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004218 WebView current = mTabControl.getCurrentWebView();
4219 if (current == null) {
4220 return;
4221 }
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004222 Intent intent = new Intent(this,
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08004223 CombinedBookmarkHistoryActivity.class);
The Android Open Source Project765e7c92009-01-09 17:51:25 -08004224 String title = current.getTitle();
4225 String url = current.getUrl();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004226 // Just in case the user opens bookmarks before a page finishes loading
4227 // so the current history item, and therefore the page, is null.
4228 if (null == url) {
4229 url = mLastEnteredUrl;
4230 // This can happen.
4231 if (null == url) {
4232 url = mSettings.getHomePage();
4233 }
4234 }
4235 // In case the web page has not yet received its associated title.
4236 if (title == null) {
4237 title = url;
4238 }
4239 intent.putExtra("title", title);
4240 intent.putExtra("url", url);
4241 intent.putExtra("maxTabsOpen",
4242 mTabControl.getTabCount() >= TabControl.MAX_TABS);
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08004243 if (startWithHistory) {
4244 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4245 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4246 }
4247 startActivityForResult(intent, COMBO_PAGE);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004248 }
4249
The Android Open Source Projected217d92008-12-17 18:05:52 -08004250 // Called when loading from context menu or LOAD_URL message
4251 private void loadURL(WebView view, String url) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004252 // In case the user enters nothing.
The Android Open Source Projected217d92008-12-17 18:05:52 -08004253 if (url != null && url.length() != 0 && view != null) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004254 url = smartUrlFilter(url);
The Android Open Source Projected217d92008-12-17 18:05:52 -08004255 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4256 view.loadUrl(url);
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004257 }
4258 }
4259 }
4260
4261 private void checkMemory() {
4262 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4263 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4264 .getMemoryInfo(mi);
4265 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4266 // mi.threshold) for now
4267 // if (mi.lowMemory) {
4268 if (mi.availMem < mi.threshold) {
4269 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4270 + (mi.availMem / 1024) + "K threshold="
4271 + (mi.threshold / 1024) + "K");
4272 mTabControl.freeMemory();
4273 }
4274 }
4275
4276 private String smartUrlFilter(Uri inUri) {
4277 if (inUri != null) {
4278 return smartUrlFilter(inUri.toString());
4279 }
4280 return null;
4281 }
4282
4283
4284 // get window count
4285
4286 int getWindowCount(){
4287 if(mTabControl != null){
4288 return mTabControl.getTabCount();
4289 }
4290 return 0;
4291 }
4292
4293 static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4294 "(?i)" + // switch on case insensitive matching
4295 "(" + // begin group for schema
4296 "(?:http|https|file):\\/\\/" +
4297 "|(?:data|about|content|javascript):" +
4298 ")" +
4299 "(.*)" );
4300
4301 /**
4302 * Attempts to determine whether user input is a URL or search
4303 * terms. Anything with a space is passed to search.
4304 *
4305 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4306 * "Http://" converts to "http://"
4307 *
4308 * @return Original or modified URL
4309 *
4310 */
The Android Open Source Projected217d92008-12-17 18:05:52 -08004311 String smartUrlFilter(String url) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004312
The Android Open Source Projected217d92008-12-17 18:05:52 -08004313 String inUrl = url.trim();
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004314 boolean hasSpace = inUrl.indexOf(' ') != -1;
4315
The Android Open Source Projected217d92008-12-17 18:05:52 -08004316 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4317 if (matcher.matches()) {
4318 if (hasSpace) {
4319 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004320 }
The Android Open Source Projected217d92008-12-17 18:05:52 -08004321 // force scheme to lowercase
4322 String scheme = matcher.group(1);
4323 String lcScheme = scheme.toLowerCase();
4324 if (!lcScheme.equals(scheme)) {
4325 return lcScheme + matcher.group(2);
4326 }
4327 return inUrl;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004328 }
4329 if (hasSpace) {
4330 // FIXME: quick search, need to be customized by setting
4331 if (inUrl.length() > 2 && inUrl.charAt(1) == ' ') {
4332 // FIXME: Is this the correct place to add to searches?
4333 // what if someone else calls this function?
4334 char char0 = inUrl.charAt(0);
4335
4336 if (char0 == 'g') {
4337 Browser.addSearchUrl(mResolver, inUrl);
4338 return composeSearchUrl(inUrl.substring(2));
4339
4340 } else if (char0 == 'w') {
4341 Browser.addSearchUrl(mResolver, inUrl);
4342 return URLUtil.composeSearchUrl(inUrl.substring(2),
4343 QuickSearch_W,
4344 QUERY_PLACE_HOLDER);
4345
4346 } else if (char0 == 'd') {
4347 Browser.addSearchUrl(mResolver, inUrl);
4348 return URLUtil.composeSearchUrl(inUrl.substring(2),
4349 QuickSearch_D,
4350 QUERY_PLACE_HOLDER);
4351
4352 } else if (char0 == 'l') {
4353 Browser.addSearchUrl(mResolver, inUrl);
4354 // FIXME: we need location in this case
4355 return URLUtil.composeSearchUrl(inUrl.substring(2),
4356 QuickSearch_L,
4357 QUERY_PLACE_HOLDER);
4358 }
4359 }
4360 } else {
4361 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4362 return URLUtil.guessUrl(inUrl);
4363 }
4364 }
4365
4366 Browser.addSearchUrl(mResolver, inUrl);
4367 return composeSearchUrl(inUrl);
4368 }
4369
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08004370 /* package */ String composeSearchUrl(String search) {
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004371 return URLUtil.composeSearchUrl(search, QuickSearch_G,
4372 QUERY_PLACE_HOLDER);
4373 }
4374
The Android Open Source Projected217d92008-12-17 18:05:52 -08004375 /* package */void setBaseSearchUrl(String url) {
4376 if (url == null || url.length() == 0) {
4377 /*
4378 * get the google search url based on the SIM. Default is US. NOTE:
4379 * This code uses resources to optionally select the search Uri,
4380 * based on the MCC value from the SIM. The default string will most
4381 * likely be fine. It is parameterized to accept info from the
4382 * Locale, the language code is the first parameter (%1$s) and the
4383 * country code is the second (%2$s). This code must function in the
4384 * same way as a similar lookup in
4385 * com.android.googlesearch.SuggestionProvider#onCreate(). If you
4386 * change either of these functions, change them both. (The same is
4387 * true for the underlying resource strings, which are stored in
4388 * mcc-specific xml files.)
4389 */
4390 Locale l = Locale.getDefault();
4391 QuickSearch_G = getResources().getString(
4392 R.string.google_search_base, l.getLanguage(),
4393 l.getCountry().toLowerCase())
4394 + "client=ms-"
4395 + SystemProperties.get("ro.com.google.clientid", "unknown")
4396 + "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&q=%s";
4397 } else {
4398 QuickSearch_G = url;
4399 }
4400 }
4401
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004402 private final static int LOCK_ICON_UNSECURE = 0;
4403 private final static int LOCK_ICON_SECURE = 1;
4404 private final static int LOCK_ICON_MIXED = 2;
4405
4406 private int mLockIconType = LOCK_ICON_UNSECURE;
4407 private int mPrevLockType = LOCK_ICON_UNSECURE;
4408
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004409 private BrowserSettings mSettings;
4410 private TabControl mTabControl;
4411 private ContentResolver mResolver;
4412 private FrameLayout mContentView;
4413 private ImageGrid mTabOverview;
4414
4415 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4416 // view, we should rewrite this.
4417 private int mCurrentMenuState = 0;
4418 private int mMenuState = R.id.MAIN_MENU;
4419 private static final int EMPTY_MENU = -1;
4420 private Menu mMenu;
4421
4422 private FindDialog mFindDialog;
4423 // Used to prevent chording to result in firing two shortcuts immediately
4424 // one after another. Fixes bug 1211714.
4425 boolean mCanChord;
4426
4427 private boolean mInLoad;
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08004428 private boolean mIsNetworkUp;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004429
4430 private boolean mPageStarted;
4431 private boolean mActivityInPause = true;
4432
4433 private boolean mMenuIsDown;
4434
4435 private final KeyTracker mKeyTracker = new KeyTracker(this);
4436
4437 // As trackball doesn't send repeat down, we have to track it ourselves
4438 private boolean mTrackTrackball;
4439
4440 private static boolean mInTrace;
4441
4442 // Performance probe
4443 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4444 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4445 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4446 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4447 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4448 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4449 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4450 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4451 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4452 };
4453
4454 private long mStart;
4455 private long mProcessStart;
4456 private long mUserStart;
4457 private long mSystemStart;
4458 private long mIdleStart;
4459 private long mIrqStart;
4460
4461 private long mUiStart;
4462
4463 private Drawable mMixLockIcon;
4464 private Drawable mSecLockIcon;
4465 private Drawable mGenericFavicon;
4466
4467 /* hold a ref so we can auto-cancel if necessary */
4468 private AlertDialog mAlertDialog;
4469
4470 // Wait for credentials before loading google.com
4471 private ProgressDialog mCredsDlg;
4472
4473 // The up-to-date URL and title (these can be different from those stored
4474 // in WebView, since it takes some time for the information in WebView to
4475 // get updated)
4476 private String mUrl;
4477 private String mTitle;
4478
4479 // As PageInfo has different style for landscape / portrait, we have
4480 // to re-open it when configuration changed
4481 private AlertDialog mPageInfoDialog;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004482 private TabControl.Tab mPageInfoView;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004483 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4484 // dialog, we should not just dismiss it, but should get back to the
4485 // SSL-certificate-on-error dialog. This flag is used to store this state
4486 private Boolean mPageInfoFromShowSSLCertificateOnError;
4487
4488 // as SSLCertificateOnError has different style for landscape / portrait,
4489 // we have to re-open it when configuration changed
4490 private AlertDialog mSSLCertificateOnErrorDialog;
4491 private WebView mSSLCertificateOnErrorView;
4492 private SslErrorHandler mSSLCertificateOnErrorHandler;
4493 private SslError mSSLCertificateOnErrorError;
4494
4495 // as SSLCertificate has different style for landscape / portrait, we
4496 // have to re-open it when configuration changed
4497 private AlertDialog mSSLCertificateDialog;
The Android Open Source Projected217d92008-12-17 18:05:52 -08004498 private TabControl.Tab mSSLCertificateView;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004499
4500 // as HttpAuthentication has different style for landscape / portrait, we
4501 // have to re-open it when configuration changed
4502 private AlertDialog mHttpAuthenticationDialog;
4503 private HttpAuthHandler mHttpAuthHandler;
4504
4505 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4506 new FrameLayout.LayoutParams(
4507 ViewGroup.LayoutParams.FILL_PARENT,
4508 ViewGroup.LayoutParams.FILL_PARENT);
4509 // We may provide UI to customize these
4510 // Google search from the browser
The Android Open Source Projected217d92008-12-17 18:05:52 -08004511 static String QuickSearch_G;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004512 // Wikipedia search
4513 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4514 // Dictionary search
4515 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4516 // Google Mobile Local search
4517 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4518
The Android Open Source Projected217d92008-12-17 18:05:52 -08004519 final static String QUERY_PLACE_HOLDER = "%s";
4520
4521 // "source" parameter for Google search through search key
4522 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
The Android Open Source Projected217d92008-12-17 18:05:52 -08004523 // "source" parameter for Google search through goto menu
4524 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4525 // "source" parameter for Google search through simplily type
4526 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4527 // "source" parameter for Google search suggested by the browser
4528 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4529 // "source" parameter for Google search from unknown source
4530 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004531
4532 private final static String LOGTAG = "browser";
4533
4534 private TabListener mTabListener;
4535
4536 private String mLastEnteredUrl;
4537
4538 private PowerManager.WakeLock mWakeLock;
4539 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4540
4541 private Toast mStopToast;
4542
4543 // Used during animations to prevent other animations from being triggered.
4544 // A count is used since the animation to and from the Window overview can
4545 // overlap. A count of 0 means no animation where a count of > 0 means
4546 // there are animations in progress.
4547 private int mAnimationCount;
The Android Open Source Project066e9082009-01-20 14:03:59 -08004548
The Android Open Source Projected217d92008-12-17 18:05:52 -08004549 // As the ids are dynamically created, we can't guarantee that they will
4550 // be in sequence, so this static array maps ids to a window number.
The Android Open Source Project066e9082009-01-20 14:03:59 -08004551 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
The Android Open Source Projected217d92008-12-17 18:05:52 -08004552 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4553 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4554 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004555
4556 // monitor platform changes
4557 private IntentFilter mNetworkStateChangedFilter;
4558 private BroadcastReceiver mNetworkStateIntentReceiver;
4559
4560 // activity requestCode
The Android Open Source Projectb7775e12009-02-10 15:44:04 -08004561 final static int COMBO_PAGE = 1;
4562 final static int DOWNLOAD_PAGE = 2;
4563 final static int PREFERENCES_PAGE = 3;
The Android Open Source Projectba6d7b82008-10-21 07:00:00 -07004564
4565 // the frenquency of checking whether system memory is low
4566 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
4567}