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