blob: 5c4a63d16c11fb625dc222d103ad41db5c8f177d [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;
21
22import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080023import android.app.AlertDialog;
24import android.app.ProgressDialog;
25import android.app.SearchManager;
26import android.content.ActivityNotFoundException;
27import android.content.BroadcastReceiver;
28import android.content.ComponentName;
29import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040030import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ContentValues;
32import android.content.Context;
33import android.content.DialogInterface;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.content.ServiceConnection;
37import android.content.DialogInterface.OnCancelListener;
Grace Klobab4da0ad2009-05-14 14:45:40 -070038import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080039import android.content.pm.PackageManager;
40import android.content.pm.ResolveInfo;
41import android.content.res.AssetManager;
42import android.content.res.Configuration;
43import android.content.res.Resources;
44import android.database.Cursor;
45import android.database.sqlite.SQLiteDatabase;
46import android.database.sqlite.SQLiteException;
47import android.graphics.Bitmap;
48import android.graphics.Canvas;
49import android.graphics.Color;
50import android.graphics.DrawFilter;
51import android.graphics.Paint;
52import android.graphics.PaintFlagsDrawFilter;
53import android.graphics.Picture;
54import android.graphics.drawable.BitmapDrawable;
55import android.graphics.drawable.Drawable;
56import android.graphics.drawable.LayerDrawable;
57import android.graphics.drawable.PaintDrawable;
58import android.hardware.SensorListener;
59import android.hardware.SensorManager;
60import android.net.ConnectivityManager;
61import android.net.Uri;
62import android.net.WebAddress;
63import android.net.http.EventHandler;
64import android.net.http.SslCertificate;
65import android.net.http.SslError;
66import android.os.AsyncTask;
67import android.os.Bundle;
68import android.os.Debug;
69import android.os.Environment;
70import android.os.Handler;
71import android.os.IBinder;
72import android.os.Message;
73import android.os.PowerManager;
74import android.os.Process;
75import android.os.RemoteException;
76import android.os.ServiceManager;
77import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.provider.Browser;
79import android.provider.Contacts;
80import android.provider.Downloads;
81import android.provider.MediaStore;
82import android.provider.Contacts.Intents.Insert;
83import android.text.IClipboard;
84import android.text.TextUtils;
85import android.text.format.DateFormat;
86import android.text.util.Regex;
The Android Open Source Project0c908882009-03-03 19:32:16 -080087import android.util.Log;
88import android.view.ContextMenu;
89import android.view.Gravity;
90import android.view.KeyEvent;
91import android.view.LayoutInflater;
92import android.view.Menu;
93import android.view.MenuInflater;
94import android.view.MenuItem;
95import android.view.View;
96import android.view.ViewGroup;
97import android.view.Window;
98import android.view.WindowManager;
99import android.view.ContextMenu.ContextMenuInfo;
100import android.view.MenuItem.OnMenuItemClickListener;
101import android.view.animation.AlphaAnimation;
102import android.view.animation.Animation;
103import android.view.animation.AnimationSet;
104import android.view.animation.DecelerateInterpolator;
105import android.view.animation.ScaleAnimation;
106import android.view.animation.TranslateAnimation;
107import android.webkit.CookieManager;
108import android.webkit.CookieSyncManager;
109import android.webkit.DownloadListener;
Steve Block2bc69912009-07-30 14:45:13 +0100110import android.webkit.GeolocationPermissions;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -0700112import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import android.webkit.SslErrorHandler;
114import android.webkit.URLUtil;
115import android.webkit.WebChromeClient;
Andrei Popescuc9b55562009-07-07 10:51:15 +0100116import android.webkit.WebChromeClient.CustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import android.webkit.WebHistoryItem;
118import android.webkit.WebIconDatabase;
Ben Murdoch092dd5d2009-04-22 12:34:12 +0100119import android.webkit.WebStorage;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import android.webkit.WebView;
121import android.webkit.WebViewClient;
122import android.widget.EditText;
123import android.widget.FrameLayout;
124import android.widget.LinearLayout;
125import android.widget.TextView;
126import android.widget.Toast;
127
128import java.io.BufferedOutputStream;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400129import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130import java.io.File;
131import java.io.FileInputStream;
132import java.io.FileOutputStream;
133import java.io.IOException;
134import java.io.InputStream;
135import java.net.MalformedURLException;
136import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700137import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800138import java.net.URL;
139import java.net.URLEncoder;
140import java.text.ParseException;
141import java.util.Date;
142import java.util.Enumeration;
143import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700144import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800145import java.util.Vector;
146import java.util.regex.Matcher;
147import java.util.regex.Pattern;
148import java.util.zip.ZipEntry;
149import java.util.zip.ZipFile;
150
151public class BrowserActivity extends Activity
152 implements KeyTracker.OnKeyTracker,
153 View.OnCreateContextMenuListener,
154 DownloadListener {
155
Dave Bort31a6d1c2009-04-13 15:56:49 -0700156 /* Define some aliases to make these debugging flags easier to refer to.
157 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
158 */
159 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
160 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
161 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
162
The Android Open Source Project0c908882009-03-03 19:32:16 -0800163 private IGoogleLoginService mGls = null;
164 private ServiceConnection mGlsConnection = null;
165
166 private SensorManager mSensorManager = null;
167
Satish Sampath565505b2009-05-29 15:37:27 +0100168 // These are single-character shortcuts for searching popular sources.
169 private static final int SHORTCUT_INVALID = 0;
170 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
171 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
172 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
173 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
174
The Android Open Source Project0c908882009-03-03 19:32:16 -0800175 /* Whitelisted webpages
176 private static HashSet<String> sWhiteList;
177
178 static {
179 sWhiteList = new HashSet<String>();
180 sWhiteList.add("cnn.com/");
181 sWhiteList.add("espn.go.com/");
182 sWhiteList.add("nytimes.com/");
183 sWhiteList.add("engadget.com/");
184 sWhiteList.add("yahoo.com/");
185 sWhiteList.add("msn.com/");
186 sWhiteList.add("amazon.com/");
187 sWhiteList.add("consumerist.com/");
188 sWhiteList.add("google.com/m/news");
189 }
190 */
191
192 private void setupHomePage() {
193 final Runnable getAccount = new Runnable() {
194 public void run() {
195 // Lower priority
196 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
197 // get the default home page
198 String homepage = mSettings.getHomePage();
199
200 try {
201 if (mGls == null) return;
202
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700203 if (!homepage.startsWith("http://www.google.")) return;
204 if (homepage.indexOf('?') == -1) return;
205
The Android Open Source Project0c908882009-03-03 19:32:16 -0800206 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
207 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
208
209 // three cases:
210 //
211 // hostedUser == googleUser
212 // The device has only a google account
213 //
214 // hostedUser != googleUser
215 // The device has a hosted account and a google account
216 //
217 // hostedUser != null, googleUser == null
218 // The device has only a hosted account (so far)
219
220 // developers might have no accounts at all
221 if (hostedUser == null) return;
222
223 if (googleUser == null || !hostedUser.equals(googleUser)) {
224 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700225 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800226 }
227 } catch (RemoteException ignore) {
228 // Login service died; carry on
229 } catch (RuntimeException ignore) {
230 // Login service died; carry on
231 } finally {
232 finish(homepage);
233 }
234 }
235
236 private void finish(final String homepage) {
237 mHandler.post(new Runnable() {
238 public void run() {
239 mSettings.setHomePage(BrowserActivity.this, homepage);
240 resumeAfterCredentials();
241
242 // as this is running in a separate thread,
243 // BrowserActivity's onDestroy() may have been called,
244 // which also calls unbindService().
245 if (mGlsConnection != null) {
246 // we no longer need to keep GLS open
247 unbindService(mGlsConnection);
248 mGlsConnection = null;
249 }
250 } });
251 } };
252
253 final boolean[] done = { false };
254
255 // Open a connection to the Google Login Service. The first
256 // time the connection is established, set up the homepage depending on
257 // the account in a background thread.
258 mGlsConnection = new ServiceConnection() {
259 public void onServiceConnected(ComponentName className, IBinder service) {
260 mGls = IGoogleLoginService.Stub.asInterface(service);
261 if (done[0] == false) {
262 done[0] = true;
263 Thread account = new Thread(getAccount);
264 account.setName("GLSAccount");
265 account.start();
266 }
267 }
268 public void onServiceDisconnected(ComponentName className) {
269 mGls = null;
270 }
271 };
272
273 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
274 mGlsConnection, Context.BIND_AUTO_CREATE);
275 }
276
277 /**
278 * This class is in charge of installing pre-packaged plugins
279 * from the Browser assets directory to the user's data partition.
280 * Plugins are loaded from the "plugins" directory in the assets;
281 * Anything that is in this directory will be copied over to the
282 * user data partition in app_plugins.
283 */
Cary Clarka9771242009-08-11 16:42:26 -0400284 private static class CopyPlugins implements Runnable {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800285 final static String TAG = "PluginsInstaller";
286 final static String ZIP_FILTER = "assets/plugins/";
287 final static String APK_PATH = "/system/app/Browser.apk";
288 final static String PLUGIN_EXTENSION = ".so";
289 final static String TEMPORARY_EXTENSION = "_temp";
290 final static String BUILD_INFOS_FILE = "build.prop";
291 final static String SYSTEM_BUILD_INFOS_FILE = "/system/"
292 + BUILD_INFOS_FILE;
Cary Clark87553722009-08-11 14:19:06 -0400293 final static int BUFSIZE = 4096;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800294 boolean mDoOverwrite = false;
295 String pluginsPath;
296 Context mContext;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800297
298 public CopyPlugins (boolean overwrite, Context context) {
299 mDoOverwrite = overwrite;
300 mContext = context;
301 }
302
303 /**
304 * Returned a filtered list of ZipEntry.
305 * We list all the files contained in the zip and
306 * only returns the ones starting with the ZIP_FILTER
307 * path.
308 *
309 * @param zip the zip file used.
310 */
311 public Vector<ZipEntry> pluginsFilesFromZip(ZipFile zip) {
312 Vector<ZipEntry> list = new Vector<ZipEntry>();
313 Enumeration entries = zip.entries();
314 while (entries.hasMoreElements()) {
315 ZipEntry entry = (ZipEntry) entries.nextElement();
316 if (entry.getName().startsWith(ZIP_FILTER)) {
317 list.add(entry);
318 }
319 }
320 return list;
321 }
322
323 /**
324 * Utility method to copy the content from an inputstream
325 * to a file output stream.
326 */
327 public void copyStreams(InputStream is, FileOutputStream fos) {
328 BufferedOutputStream os = null;
329 try {
330 byte data[] = new byte[BUFSIZE];
331 int count;
332 os = new BufferedOutputStream(fos, BUFSIZE);
333 while ((count = is.read(data, 0, BUFSIZE)) != -1) {
334 os.write(data, 0, count);
335 }
336 os.flush();
337 } catch (IOException e) {
338 Log.e(TAG, "Exception while copying: " + e);
339 } finally {
340 try {
341 if (os != null) {
342 os.close();
343 }
344 } catch (IOException e2) {
345 Log.e(TAG, "Exception while closing the stream: " + e2);
346 }
347 }
348 }
349
350 /**
351 * Returns a string containing the contents of a file
352 *
353 * @param file the target file
354 */
355 private String contentsOfFile(File file) {
356 String ret = null;
357 FileInputStream is = null;
358 try {
359 byte[] buffer = new byte[BUFSIZE];
360 int count;
361 is = new FileInputStream(file);
362 StringBuffer out = new StringBuffer();
363
364 while ((count = is.read(buffer, 0, BUFSIZE)) != -1) {
365 out.append(new String(buffer, 0, count));
366 }
367 ret = out.toString();
368 } catch (IOException e) {
369 Log.e(TAG, "Exception getting contents of file " + e);
370 } finally {
371 if (is != null) {
372 try {
373 is.close();
374 } catch (IOException e2) {
375 Log.e(TAG, "Exception while closing the file: " + e2);
376 }
377 }
378 }
379 return ret;
380 }
381
382 /**
383 * Utility method to initialize the user data plugins path.
384 */
385 public void initPluginsPath() {
386 BrowserSettings s = BrowserSettings.getInstance();
387 pluginsPath = s.getPluginsPath();
388 if (pluginsPath == null) {
389 s.loadFromDb(mContext);
390 pluginsPath = s.getPluginsPath();
391 }
Dave Bort31a6d1c2009-04-13 15:56:49 -0700392 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800393 Log.v(TAG, "Plugin path: " + pluginsPath);
394 }
395 }
396
397 /**
398 * Utility method to delete a file or a directory
399 *
400 * @param file the File to delete
401 */
402 public void deleteFile(File file) {
403 File[] files = file.listFiles();
404 if ((files != null) && files.length > 0) {
405 for (int i=0; i< files.length; i++) {
406 deleteFile(files[i]);
407 }
408 }
409 if (!file.delete()) {
410 Log.e(TAG, file.getPath() + " could not get deleted");
411 }
412 }
413
414 /**
415 * Clean the content of the plugins directory.
416 * We delete the directory, then recreate it.
417 */
418 public void cleanPluginsDirectory() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700419 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800420 Log.v(TAG, "delete plugins directory: " + pluginsPath);
421 }
422 File pluginsDirectory = new File(pluginsPath);
423 deleteFile(pluginsDirectory);
424 pluginsDirectory.mkdir();
425 }
426
427
428 /**
429 * Copy the SYSTEM_BUILD_INFOS_FILE file containing the
430 * informations about the system build to the
431 * BUILD_INFOS_FILE in the plugins directory.
432 */
433 public void copyBuildInfos() {
Cary Clark722f7552009-08-11 17:40:45 -0400434 FileInputStream iStream = null;
435 FileOutputStream oStream = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800436 try {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700437 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800438 Log.v(TAG, "Copy build infos to the plugins directory");
439 }
440 File buildInfoFile = new File(SYSTEM_BUILD_INFOS_FILE);
441 File buildInfoPlugins = new File(pluginsPath, BUILD_INFOS_FILE);
Cary Clark722f7552009-08-11 17:40:45 -0400442 iStream = new FileInputStream(buildInfoFile);
443 oStream = new FileOutputStream(buildInfoPlugins);
444 copyStreams(iStream, oStream);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800445 } catch (IOException e) {
446 Log.e(TAG, "Exception while copying the build infos: " + e);
Cary Clark722f7552009-08-11 17:40:45 -0400447 } finally {
448 try {
449 if (iStream != null) {
450 iStream.close();
451 }
452 } catch (IOException e2) {
453 Log.e(TAG, "Exception while closing the input stream: " + e2);
454 }
455 try {
456 if (oStream != null) {
457 oStream.close();
458 }
459 } catch (IOException e3) {
460 Log.e(TAG, "Exception while closing the output stream: " + e3);
461 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800462 }
463 }
464
465 /**
466 * Returns true if the current system is newer than the
467 * system that installed the plugins.
468 * We determinate this by checking the build number of the system.
469 *
470 * At the end of the plugins copy operation, we copy the
471 * SYSTEM_BUILD_INFOS_FILE to the BUILD_INFOS_FILE.
472 * We then just have to load both and compare them -- if they
473 * are different the current system is newer.
474 *
475 * Loading and comparing the strings should be faster than
476 * creating a hash, the files being rather small. Extracting the
477 * version number would require some parsing which may be more
478 * brittle.
479 */
480 public boolean newSystemImage() {
481 try {
482 File buildInfoFile = new File(SYSTEM_BUILD_INFOS_FILE);
483 File buildInfoPlugins = new File(pluginsPath, BUILD_INFOS_FILE);
484 if (!buildInfoPlugins.exists()) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700485 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800486 Log.v(TAG, "build.prop in plugins directory " + pluginsPath
487 + " does not exist, therefore it's a new system image");
488 }
489 return true;
490 } else {
491 String buildInfo = contentsOfFile(buildInfoFile);
492 String buildInfoPlugin = contentsOfFile(buildInfoPlugins);
493 if (buildInfo == null || buildInfoPlugin == null
494 || buildInfo.compareTo(buildInfoPlugin) != 0) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700495 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800496 Log.v(TAG, "build.prop are different, "
497 + " therefore it's a new system image");
498 }
499 return true;
500 }
501 }
502 } catch (Exception e) {
503 Log.e(TAG, "Exc in newSystemImage(): " + e);
504 }
505 return false;
506 }
507
508 /**
509 * Check if the version of the plugins contained in the
510 * Browser assets is the same as the version of the plugins
511 * in the plugins directory.
512 * We simply iterate on every file in the assets/plugins
513 * and return false if a file listed in the assets does
514 * not exist in the plugins directory.
515 */
516 private boolean checkIsDifferentVersions() {
517 try {
518 ZipFile zip = new ZipFile(APK_PATH);
519 Vector<ZipEntry> files = pluginsFilesFromZip(zip);
520 int zipFilterLength = ZIP_FILTER.length();
521
522 Enumeration entries = files.elements();
523 while (entries.hasMoreElements()) {
524 ZipEntry entry = (ZipEntry) entries.nextElement();
525 String path = entry.getName().substring(zipFilterLength);
526 File outputFile = new File(pluginsPath, path);
527 if (!outputFile.exists()) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700528 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800529 Log.v(TAG, "checkIsDifferentVersions(): extracted file "
530 + path + " does not exist, we have a different version");
531 }
532 return true;
533 }
534 }
535 } catch (IOException e) {
536 Log.e(TAG, "Exception in checkDifferentVersions(): " + e);
537 }
538 return false;
539 }
540
541 /**
542 * Copy every files from the assets/plugins directory
543 * to the app_plugins directory in the data partition.
544 * Once copied, we copy over the SYSTEM_BUILD_INFOS file
545 * in the plugins directory.
546 *
547 * NOTE: we directly access the content from the Browser
548 * package (it's a zip file) and do not use AssetManager
549 * as there is a limit of 1Mb (see Asset.h)
550 */
551 public void run() {
552 // Lower the priority
553 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
554 try {
555 if (pluginsPath == null) {
556 Log.e(TAG, "No plugins path found!");
557 return;
558 }
559
560 ZipFile zip = new ZipFile(APK_PATH);
561 Vector<ZipEntry> files = pluginsFilesFromZip(zip);
562 Vector<File> plugins = new Vector<File>();
563 int zipFilterLength = ZIP_FILTER.length();
564
565 Enumeration entries = files.elements();
566 while (entries.hasMoreElements()) {
567 ZipEntry entry = (ZipEntry) entries.nextElement();
568 String path = entry.getName().substring(zipFilterLength);
569 File outputFile = new File(pluginsPath, path);
570 outputFile.getParentFile().mkdirs();
571
572 if (outputFile.exists() && !mDoOverwrite) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700573 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800574 Log.v(TAG, path + " already extracted.");
575 }
576 } else {
577 if (path.endsWith(PLUGIN_EXTENSION)) {
578 // We rename plugins to be sure a half-copied
579 // plugin is not loaded by the browser.
580 plugins.add(outputFile);
581 outputFile = new File(pluginsPath,
582 path + TEMPORARY_EXTENSION);
583 }
584 FileOutputStream fos = new FileOutputStream(outputFile);
Dave Bort31a6d1c2009-04-13 15:56:49 -0700585 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800586 Log.v(TAG, "copy " + entry + " to "
587 + pluginsPath + "/" + path);
588 }
589 copyStreams(zip.getInputStream(entry), fos);
590 }
591 }
592
593 // We now rename the .so we copied, once all their resources
594 // are safely copied over to the user data partition.
595 Enumeration elems = plugins.elements();
596 while (elems.hasMoreElements()) {
597 File renamedFile = (File) elems.nextElement();
598 File sourceFile = new File(renamedFile.getPath()
599 + TEMPORARY_EXTENSION);
Dave Bort31a6d1c2009-04-13 15:56:49 -0700600 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800601 Log.v(TAG, "rename " + sourceFile.getPath()
602 + " to " + renamedFile.getPath());
603 }
604 sourceFile.renameTo(renamedFile);
605 }
606
607 copyBuildInfos();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800608 } catch (IOException e) {
609 Log.e(TAG, "IO Exception: " + e);
610 }
611 }
612 };
613
614 /**
615 * Copy the content of assets/plugins/ to the app_plugins directory
616 * in the data partition.
617 *
618 * This function is called every time the browser is started.
619 * We first check if the system image is newer than the one that
620 * copied the plugins (if there's plugins in the data partition).
621 * If this is the case, we then check if the versions are different.
622 * If they are different, we clean the plugins directory in the
623 * data partition, then start a thread to copy the plugins while
624 * the browser continue to load.
625 *
626 * @param overwrite if true overwrite the files even if they are
627 * already present (to let the user "reset" the plugins if needed).
628 */
629 private void copyPlugins(boolean overwrite) {
630 CopyPlugins copyPluginsFromAssets = new CopyPlugins(overwrite, this);
631 copyPluginsFromAssets.initPluginsPath();
632 if (copyPluginsFromAssets.newSystemImage()) {
633 if (copyPluginsFromAssets.checkIsDifferentVersions()) {
634 copyPluginsFromAssets.cleanPluginsDirectory();
635 Thread copyplugins = new Thread(copyPluginsFromAssets);
636 copyplugins.setName("CopyPlugins");
637 copyplugins.start();
638 }
639 }
640 }
641
Cary Clarka9771242009-08-11 16:42:26 -0400642 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800643 @Override
644 public Void doInBackground(File... files) {
645 if (files != null) {
646 for (File f : files) {
647 f.delete();
648 }
649 }
650 return null;
651 }
652 }
653
Leon Scroggins81db3662009-06-04 17:45:11 -0400654 // Flag to enable the touchable browser bar with buttons
655 private final boolean CUSTOM_BROWSER_BAR = true;
656
The Android Open Source Project0c908882009-03-03 19:32:16 -0800657 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700658 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800659 Log.v(LOGTAG, this + " onStart");
660 }
661 super.onCreate(icicle);
Leon Scroggins81db3662009-06-04 17:45:11 -0400662 if (CUSTOM_BROWSER_BAR) {
663 this.requestWindowFeature(Window.FEATURE_NO_TITLE);
Leon Scroggins81db3662009-06-04 17:45:11 -0400664 } else {
665 this.requestWindowFeature(Window.FEATURE_LEFT_ICON);
666 this.requestWindowFeature(Window.FEATURE_RIGHT_ICON);
667 this.requestWindowFeature(Window.FEATURE_PROGRESS);
668 this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
669 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800670 // test the browser in OpenGL
671 // requestWindowFeature(Window.FEATURE_OPENGL);
672
673 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
674
675 mResolver = getContentResolver();
676
The Android Open Source Project0c908882009-03-03 19:32:16 -0800677 //
678 // start MASF proxy service
679 //
680 //Intent proxyServiceIntent = new Intent();
681 //proxyServiceIntent.setComponent
682 // (new ComponentName(
683 // "com.android.masfproxyservice",
684 // "com.android.masfproxyservice.MasfProxyService"));
685 //startService(proxyServiceIntent, null);
686
687 mSecLockIcon = Resources.getSystem().getDrawable(
688 android.R.drawable.ic_secure);
689 mMixLockIcon = Resources.getSystem().getDrawable(
690 android.R.drawable.ic_partial_secure);
691 mGenericFavicon = getResources().getDrawable(
692 R.drawable.app_web_browser_sm);
693
Leon Scroggins81db3662009-06-04 17:45:11 -0400694 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
695 .findViewById(com.android.internal.R.id.content);
696 if (CUSTOM_BROWSER_BAR) {
Andrei Popescuadc008d2009-06-26 14:11:30 +0100697 // This FrameLayout will hold the custom FrameLayout and a LinearLayout
698 // that contains the title bar and a FrameLayout, which
Leon Scroggins81db3662009-06-04 17:45:11 -0400699 // holds everything else.
Andrei Popescuadc008d2009-06-26 14:11:30 +0100700 FrameLayout browserFrameLayout = (FrameLayout) LayoutInflater.from(this)
Leon Scrogginse4b3bda2009-06-09 15:46:41 -0400701 .inflate(R.layout.custom_screen, null);
Andrei Popescuadc008d2009-06-26 14:11:30 +0100702 mTitleBar = (TitleBar) browserFrameLayout.findViewById(R.id.title_bar);
Leon Scrogginse4b3bda2009-06-09 15:46:41 -0400703 mTitleBar.setBrowserActivity(this);
Andrei Popescuadc008d2009-06-26 14:11:30 +0100704 mContentView = (FrameLayout) browserFrameLayout.findViewById(
Leon Scrogginse4b3bda2009-06-09 15:46:41 -0400705 R.id.main_content);
Ben Murdochbff2d602009-07-01 20:19:05 +0100706 mErrorConsoleContainer = (LinearLayout) browserFrameLayout.findViewById(
707 R.id.error_console);
Andrei Popescuadc008d2009-06-26 14:11:30 +0100708 mCustomViewContainer = (FrameLayout) browserFrameLayout
709 .findViewById(R.id.fullscreen_custom_content);
710 frameLayout.addView(browserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins81db3662009-06-04 17:45:11 -0400711 } else {
Andrei Popescuadc008d2009-06-26 14:11:30 +0100712 mCustomViewContainer = new FrameLayout(this);
Andrei Popescu78f75702009-06-26 16:50:04 +0100713 mCustomViewContainer.setBackgroundColor(Color.BLACK);
Andrei Popescuadc008d2009-06-26 14:11:30 +0100714 mContentView = new FrameLayout(this);
Ben Murdochbff2d602009-07-01 20:19:05 +0100715
716 LinearLayout linearLayout = new LinearLayout(this);
717 linearLayout.setOrientation(LinearLayout.VERTICAL);
718 mErrorConsoleContainer = new LinearLayout(this);
719 linearLayout.addView(mErrorConsoleContainer, new LinearLayout.LayoutParams(
720 ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
721 linearLayout.addView(mContentView, COVER_SCREEN_PARAMS);
Andrei Popescuadc008d2009-06-26 14:11:30 +0100722 frameLayout.addView(mCustomViewContainer, COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +0100723 frameLayout.addView(linearLayout, COVER_SCREEN_PARAMS);
Leon Scroggins81db3662009-06-04 17:45:11 -0400724 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800725
726 // Create the tab control and our initial tab
727 mTabControl = new TabControl(this);
728
729 // Open the icon database and retain all the bookmark urls for favicons
730 retainIconsOnStartup();
731
732 // Keep a settings instance handy.
733 mSettings = BrowserSettings.getInstance();
734 mSettings.setTabControl(mTabControl);
735 mSettings.loadFromDb(this);
736
737 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
738 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
739
Grace Klobaa34f6862009-07-31 16:28:17 -0700740 /* enables registration for changes in network status from
741 http stack */
742 mNetworkStateChangedFilter = new IntentFilter();
743 mNetworkStateChangedFilter.addAction(
744 ConnectivityManager.CONNECTIVITY_ACTION);
745 mNetworkStateIntentReceiver = new BroadcastReceiver() {
746 @Override
747 public void onReceive(Context context, Intent intent) {
748 if (intent.getAction().equals(
749 ConnectivityManager.CONNECTIVITY_ACTION)) {
750 boolean down = intent.getBooleanExtra(
751 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
752 onNetworkToggle(!down);
753 }
754 }
755 };
756
Grace Kloba615c6c92009-08-03 10:22:44 -0700757 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
758 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
759 filter.addDataScheme("package");
760 mPackageInstallationReceiver = new BroadcastReceiver() {
761 @Override
762 public void onReceive(Context context, Intent intent) {
763 final String action = intent.getAction();
764 final String packageName = intent.getData()
765 .getSchemeSpecificPart();
766 final boolean replacing = intent.getBooleanExtra(
767 Intent.EXTRA_REPLACING, false);
768 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
769 // if it is replacing, refreshPlugins() when adding
770 return;
771 }
772 PackageManager pm = BrowserActivity.this.getPackageManager();
773 PackageInfo pkgInfo = null;
774 try {
775 pkgInfo = pm.getPackageInfo(packageName,
776 PackageManager.GET_PERMISSIONS);
777 } catch (PackageManager.NameNotFoundException e) {
778 return;
779 }
780 if (pkgInfo != null) {
781 String permissions[] = pkgInfo.requestedPermissions;
782 if (permissions == null) {
783 return;
784 }
785 boolean permissionOk = false;
786 for (String permit : permissions) {
787 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
788 permissionOk = true;
789 break;
790 }
791 }
792 if (permissionOk) {
793 PluginManager.getInstance(BrowserActivity.this)
794 .refreshPlugins(
795 Intent.ACTION_PACKAGE_ADDED
796 .equals(action));
797 }
798 }
799 }
800 };
801 registerReceiver(mPackageInstallationReceiver, filter);
802
Satish Sampath565505b2009-05-29 15:37:27 +0100803 // If this was a web search request, pass it on to the default web search provider.
804 if (handleWebSearchIntent(getIntent())) {
805 moveTaskToBack(true);
806 return;
807 }
808
The Android Open Source Project0c908882009-03-03 19:32:16 -0800809 if (!mTabControl.restoreState(icicle)) {
810 // clear up the thumbnail directory if we can't restore the state as
811 // none of the files in the directory are referenced any more.
812 new ClearThumbnails().execute(
813 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700814 // there is no quit on Android. But if we can't restore the state,
815 // we can treat it as a new Browser, remove the old session cookies.
816 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800817 final Intent intent = getIntent();
818 final Bundle extra = intent.getExtras();
819 // Create an initial tab.
820 // If the intent is ACTION_VIEW and data is not null, the Browser is
821 // invoked to view the content by another application. In this case,
822 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700823 UrlData urlData = getUrlDataFromIntent(intent);
824
The Android Open Source Project0c908882009-03-03 19:32:16 -0800825 final TabControl.Tab t = mTabControl.createNewTab(
826 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700827 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700828 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800829 mTabControl.setCurrentTab(t);
830 // This is one of the only places we call attachTabToContentView
831 // without animating from the tab picker.
832 attachTabToContentView(t);
833 WebView webView = t.getWebView();
834 if (extra != null) {
835 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
836 if (scale > 0 && scale <= 1000) {
837 webView.setInitialScale(scale);
838 }
839 }
840 // If we are not restoring from an icicle, then there is a high
841 // likely hood this is the first run. So, check to see if the
842 // homepage needs to be configured and copy any plugins from our
843 // asset directory to the data partition.
844 if ((extra == null || !extra.getBoolean("testing"))
845 && !mSettings.isLoginInitialized()) {
846 setupHomePage();
847 }
848 copyPlugins(true);
849
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700850 if (urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800851 if (mSettings.isLoginInitialized()) {
Leon Scroggins64b80f32009-08-07 12:03:34 -0400852 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800853 } else {
854 waitForCredentials();
855 }
856 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700857 if (extra != null) {
858 urlData.setPostData(extra
859 .getByteArray(Browser.EXTRA_POST_DATA));
860 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700861 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800862 }
863 } else {
864 // TabControl.restoreState() will create a new tab even if
865 // restoring the state fails. Attach it to the view here since we
866 // are not animating from the tab picker.
867 attachTabToContentView(mTabControl.getCurrentTab());
868 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700869
Feng Qianb3c02da2009-06-29 15:58:08 -0700870 // Read JavaScript flags if it exists.
871 String jsFlags = mSettings.getJsFlags();
872 if (jsFlags.trim().length() != 0) {
873 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
874 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800875 }
876
877 @Override
878 protected void onNewIntent(Intent intent) {
879 TabControl.Tab current = mTabControl.getCurrentTab();
880 // When a tab is closed on exit, the current tab index is set to -1.
881 // Reset before proceed as Browser requires the current tab to be set.
882 if (current == null) {
883 // Try to reset the tab in case the index was incorrect.
884 current = mTabControl.getTab(0);
885 if (current == null) {
886 // No tabs at all so just ignore this intent.
887 return;
888 }
889 mTabControl.setCurrentTab(current);
890 attachTabToContentView(current);
891 resetTitleAndIcon(current.getWebView());
892 }
893 final String action = intent.getAction();
894 final int flags = intent.getFlags();
895 if (Intent.ACTION_MAIN.equals(action) ||
896 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
897 // just resume the browser
898 return;
899 }
900 if (Intent.ACTION_VIEW.equals(action)
901 || Intent.ACTION_SEARCH.equals(action)
902 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
903 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100904 // If this was a search request (e.g. search query directly typed into the address bar),
905 // pass it on to the default web search provider.
906 if (handleWebSearchIntent(intent)) {
907 return;
908 }
909
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700910 UrlData urlData = getUrlDataFromIntent(intent);
911 if (urlData.isEmpty()) {
912 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800913 }
Grace Kloba81678d92009-06-30 07:09:56 -0700914 urlData.setPostData(intent
915 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700916
Grace Klobacc634032009-07-28 15:58:19 -0700917 final String appId = intent
918 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
919 if (Intent.ACTION_VIEW.equals(action)
920 && !getPackageName().equals(appId)
921 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400922 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700923 if (appTab != null) {
924 Log.i(LOGTAG, "Reusing tab for " + appId);
925 // Dismiss the subwindow if applicable.
926 dismissSubWindow(appTab);
927 // Since we might kill the WebView, remove it from the
928 // content view first.
929 removeTabFromContentView(appTab);
930 // Recreate the main WebView after destroying the old one.
931 // If the WebView has the same original url and is on that
932 // page, it can be reused.
933 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700934 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100935
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700936 if (current != appTab) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700937 showTab(appTab, needsLoad ? urlData : EMPTY_URL_DATA);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700938 } else {
939 if (mTabOverview != null && mAnimationCount == 0) {
940 sendAnimateFromOverview(appTab, false,
Grace Klobaec7eb372009-06-16 13:45:56 -0700941 needsLoad ? urlData : EMPTY_URL_DATA,
Grace Kloba8ca2c792009-05-26 15:41:51 -0700942 TAB_OVERVIEW_DELAY, null);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700943 } else {
944 // If the tab was the current tab, we have to attach
945 // it to the view system again.
946 attachTabToContentView(appTab);
947 if (needsLoad) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700948 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700949 }
950 }
951 }
952 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400953 } else {
954 // No matching application tab, try to find a regular tab
955 // with a matching url.
956 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
957 if (appTab != null) {
958 if (current != appTab) {
959 // Use EMPTY_URL_DATA so we do not reload the page
960 showTab(appTab, EMPTY_URL_DATA);
961 } else {
962 if (mTabOverview != null && mAnimationCount == 0) {
963 sendAnimateFromOverview(appTab, false,
964 EMPTY_URL_DATA, TAB_OVERVIEW_DELAY,
965 null);
966 }
967 // Don't do anything here since we are on the
968 // correct page.
969 }
970 } else {
971 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
972 // will be opened in a new tab unless we have reached
973 // MAX_TABS. Then the url will be opened in the current
974 // tab. If a new tab is created, it will have "true" for
975 // exit on close.
976 openTabAndShow(urlData, null, true, appId);
977 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700978 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800979 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700980 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800981 mSettings.toggleDebugSettings();
982 return;
983 }
984 // If the Window overview is up and we are not in the midst of
985 // an animation, animate away from the Window overview.
986 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700987 sendAnimateFromOverview(current, false, urlData,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 TAB_OVERVIEW_DELAY, null);
989 } else {
990 // Get rid of the subwindow if it exists
991 dismissSubWindow(current);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700992 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 }
994 }
995 }
996 }
997
Satish Sampath565505b2009-05-29 15:37:27 +0100998 private int parseUrlShortcut(String url) {
999 if (url == null) return SHORTCUT_INVALID;
1000
1001 // FIXME: quick search, need to be customized by setting
1002 if (url.length() > 2 && url.charAt(1) == ' ') {
1003 switch (url.charAt(0)) {
1004 case 'g': return SHORTCUT_GOOGLE_SEARCH;
1005 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
1006 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
1007 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
1008 }
1009 }
1010 return SHORTCUT_INVALID;
1011 }
1012
1013 /**
1014 * Launches the default web search activity with the query parameters if the given intent's data
1015 * are identified as plain search terms and not URLs/shortcuts.
1016 * @return true if the intent was handled and web search activity was launched, false if not.
1017 */
1018 private boolean handleWebSearchIntent(Intent intent) {
1019 if (intent == null) return false;
1020
1021 String url = null;
1022 final String action = intent.getAction();
1023 if (Intent.ACTION_VIEW.equals(action)) {
1024 url = intent.getData().toString();
1025 } else if (Intent.ACTION_SEARCH.equals(action)
1026 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
1027 || Intent.ACTION_WEB_SEARCH.equals(action)) {
1028 url = intent.getStringExtra(SearchManager.QUERY);
1029 }
Satish Sampath15e9f2d2009-06-23 22:29:49 +01001030 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
Satish Sampath565505b2009-05-29 15:37:27 +01001031 }
1032
1033 /**
1034 * Launches the default web search activity with the query parameters if the given url string
1035 * was identified as plain search terms and not URL/shortcut.
1036 * @return true if the request was handled and web search activity was launched, false if not.
1037 */
Satish Sampath15e9f2d2009-06-23 22:29:49 +01001038 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
Satish Sampath565505b2009-05-29 15:37:27 +01001039 if (inUrl == null) return false;
1040
1041 // In general, we shouldn't modify URL from Intent.
1042 // But currently, we get the user-typed URL from search box as well.
1043 String url = fixUrl(inUrl).trim();
1044
1045 // URLs and site specific search shortcuts are handled by the regular flow of control, so
1046 // return early.
1047 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +01001048 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +01001049 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
1050 return false;
1051 }
1052
1053 Browser.updateVisitedHistory(mResolver, url, false);
1054 Browser.addSearchUrl(mResolver, url);
1055
1056 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
1057 intent.addCategory(Intent.CATEGORY_DEFAULT);
1058 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +01001059 if (appData != null) {
1060 intent.putExtra(SearchManager.APP_DATA, appData);
1061 }
Grace Klobacc634032009-07-28 15:58:19 -07001062 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +01001063 startActivity(intent);
1064
1065 return true;
1066 }
1067
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001068 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001069 String url = null;
1070 if (intent != null) {
1071 final String action = intent.getAction();
1072 if (Intent.ACTION_VIEW.equals(action)) {
1073 url = smartUrlFilter(intent.getData());
1074 if (url != null && url.startsWith("content:")) {
1075 /* Append mimetype so webview knows how to display */
1076 String mimeType = intent.resolveType(getContentResolver());
1077 if (mimeType != null) {
1078 url += "?" + mimeType;
1079 }
1080 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001081 if ("inline:".equals(url)) {
1082 return new InlinedUrlData(
1083 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
1084 intent.getType(),
1085 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
1086 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
1087 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 } else if (Intent.ACTION_SEARCH.equals(action)
1089 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
1090 || Intent.ACTION_WEB_SEARCH.equals(action)) {
1091 url = intent.getStringExtra(SearchManager.QUERY);
1092 if (url != null) {
1093 mLastEnteredUrl = url;
1094 // Don't add Urls, just search terms.
1095 // Urls will get added when the page is loaded.
1096 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
1097 Browser.updateVisitedHistory(mResolver, url, false);
1098 }
1099 // In general, we shouldn't modify URL from Intent.
1100 // But currently, we get the user-typed URL from search box as well.
1101 url = fixUrl(url);
1102 url = smartUrlFilter(url);
1103 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
1104 if (url.contains(searchSource)) {
1105 String source = null;
1106 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
1107 if (appData != null) {
1108 source = appData.getString(SearchManager.SOURCE);
1109 }
1110 if (TextUtils.isEmpty(source)) {
1111 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
1112 }
1113 url = url.replace(searchSource, "&source=android-"+source+"&");
1114 }
1115 }
1116 }
1117 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001118 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001119 }
1120
1121 /* package */ static String fixUrl(String inUrl) {
1122 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
1123 return inUrl;
1124 if (inUrl.startsWith("http:") ||
1125 inUrl.startsWith("https:")) {
1126 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
1127 inUrl = inUrl.replaceFirst("/", "//");
1128 } else inUrl = inUrl.replaceFirst(":", "://");
1129 }
1130 return inUrl;
1131 }
1132
1133 /**
1134 * Looking for the pattern like this
1135 *
1136 * *
1137 * * *
1138 * *** * *******
1139 * * *
1140 * * *
1141 * *
1142 */
1143 private final SensorListener mSensorListener = new SensorListener() {
1144 private long mLastGestureTime;
1145 private float[] mPrev = new float[3];
1146 private float[] mPrevDiff = new float[3];
1147 private float[] mDiff = new float[3];
1148 private float[] mRevertDiff = new float[3];
1149
1150 public void onSensorChanged(int sensor, float[] values) {
1151 boolean show = false;
1152 float[] diff = new float[3];
1153
1154 for (int i = 0; i < 3; i++) {
1155 diff[i] = values[i] - mPrev[i];
1156 if (Math.abs(diff[i]) > 1) {
1157 show = true;
1158 }
1159 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
1160 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
1161 // start track when there is a big move, or revert
1162 mRevertDiff[i] = mDiff[i];
1163 mDiff[i] = 0;
1164 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
1165 // reset when it is flat
1166 mDiff[i] = mRevertDiff[i] = 0;
1167 }
1168 mDiff[i] += diff[i];
1169 mPrevDiff[i] = diff[i];
1170 mPrev[i] = values[i];
1171 }
1172
1173 if (false) {
1174 // only shows if we think the delta is big enough, in an attempt
1175 // to detect "serious" moves left/right or up/down
1176 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
1177 + values[0] + ", " + values[1] + ", " + values[2] + ")"
1178 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
1179 + ")");
1180 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
1181 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
1182 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
1183 + mRevertDiff[2] + ")");
1184 }
1185
1186 long now = android.os.SystemClock.uptimeMillis();
1187 if (now - mLastGestureTime > 1000) {
1188 mLastGestureTime = 0;
1189
1190 float y = mDiff[1];
1191 float z = mDiff[2];
1192 float ay = Math.abs(y);
1193 float az = Math.abs(z);
1194 float ry = mRevertDiff[1];
1195 float rz = mRevertDiff[2];
1196 float ary = Math.abs(ry);
1197 float arz = Math.abs(rz);
1198 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
1199 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
1200
1201 if ((gestY || gestZ) && !(gestY && gestZ)) {
1202 WebView view = mTabControl.getCurrentWebView();
1203
1204 if (view != null) {
1205 if (gestZ) {
1206 if (z < 0) {
1207 view.zoomOut();
1208 } else {
1209 view.zoomIn();
1210 }
1211 } else {
1212 view.flingScroll(0, Math.round(y * 100));
1213 }
1214 }
1215 mLastGestureTime = now;
1216 }
1217 }
1218 }
1219
1220 public void onAccuracyChanged(int sensor, int accuracy) {
1221 // TODO Auto-generated method stub
1222
1223 }
1224 };
1225
1226 @Override protected void onResume() {
1227 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -07001228 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001229 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
1230 }
1231
1232 if (!mActivityInPause) {
1233 Log.e(LOGTAG, "BrowserActivity is already resumed.");
1234 return;
1235 }
1236
Mike Reed7bfa63b2009-05-28 11:08:32 -04001237 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001238 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001239 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001240
1241 if (mWakeLock.isHeld()) {
1242 mHandler.removeMessages(RELEASE_WAKELOCK);
1243 mWakeLock.release();
1244 }
1245
1246 if (mCredsDlg != null) {
1247 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
1248 // In case credential request never comes back
1249 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
1250 }
1251 }
1252
1253 registerReceiver(mNetworkStateIntentReceiver,
1254 mNetworkStateChangedFilter);
1255 WebView.enablePlatformNotifications();
1256
1257 if (mSettings.doFlick()) {
1258 if (mSensorManager == null) {
1259 mSensorManager = (SensorManager) getSystemService(
1260 Context.SENSOR_SERVICE);
1261 }
1262 mSensorManager.registerListener(mSensorListener,
1263 SensorManager.SENSOR_ACCELEROMETER,
1264 SensorManager.SENSOR_DELAY_FASTEST);
1265 } else {
1266 mSensorManager = null;
1267 }
1268 }
1269
1270 /**
1271 * onSaveInstanceState(Bundle map)
1272 * onSaveInstanceState is called right before onStop(). The map contains
1273 * the saved state.
1274 */
1275 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001276 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001277 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1278 }
1279 // the default implementation requires each view to have an id. As the
1280 // browser handles the state itself and it doesn't use id for the views,
1281 // don't call the default implementation. Otherwise it will trigger the
1282 // warning like this, "couldn't save which view has focus because the
1283 // focused view XXX has no id".
1284
1285 // Save all the tabs
1286 mTabControl.saveState(outState);
1287 }
1288
1289 @Override protected void onPause() {
1290 super.onPause();
1291
1292 if (mActivityInPause) {
1293 Log.e(LOGTAG, "BrowserActivity is already paused.");
1294 return;
1295 }
1296
Mike Reed7bfa63b2009-05-28 11:08:32 -04001297 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001298 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001299 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001300 mWakeLock.acquire();
1301 mHandler.sendMessageDelayed(mHandler
1302 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1303 }
1304
1305 // Clear the credentials toast if it is up
1306 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1307 mCredsDlg.dismiss();
1308 }
1309 mCredsDlg = null;
1310
1311 cancelStopToast();
1312
1313 // unregister network state listener
1314 unregisterReceiver(mNetworkStateIntentReceiver);
1315 WebView.disablePlatformNotifications();
1316
1317 if (mSensorManager != null) {
1318 mSensorManager.unregisterListener(mSensorListener);
1319 }
1320 }
1321
1322 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001323 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001324 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1325 }
1326 super.onDestroy();
1327 // Remove the current tab and sub window
1328 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001329 if (t != null) {
1330 dismissSubWindow(t);
1331 removeTabFromContentView(t);
1332 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001333 // Destroy all the tabs
1334 mTabControl.destroy();
1335 WebIconDatabase.getInstance().close();
1336 if (mGlsConnection != null) {
1337 unbindService(mGlsConnection);
1338 mGlsConnection = null;
1339 }
1340
1341 //
1342 // stop MASF proxy service
1343 //
1344 //Intent proxyServiceIntent = new Intent();
1345 //proxyServiceIntent.setComponent
1346 // (new ComponentName(
1347 // "com.android.masfproxyservice",
1348 // "com.android.masfproxyservice.MasfProxyService"));
1349 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001350
1351 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001352 }
1353
1354 @Override
1355 public void onConfigurationChanged(Configuration newConfig) {
1356 super.onConfigurationChanged(newConfig);
1357
1358 if (mPageInfoDialog != null) {
1359 mPageInfoDialog.dismiss();
1360 showPageInfo(
1361 mPageInfoView,
1362 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1363 }
1364 if (mSSLCertificateDialog != null) {
1365 mSSLCertificateDialog.dismiss();
1366 showSSLCertificate(
1367 mSSLCertificateView);
1368 }
1369 if (mSSLCertificateOnErrorDialog != null) {
1370 mSSLCertificateOnErrorDialog.dismiss();
1371 showSSLCertificateOnError(
1372 mSSLCertificateOnErrorView,
1373 mSSLCertificateOnErrorHandler,
1374 mSSLCertificateOnErrorError);
1375 }
1376 if (mHttpAuthenticationDialog != null) {
1377 String title = ((TextView) mHttpAuthenticationDialog
1378 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1379 .toString();
1380 String name = ((TextView) mHttpAuthenticationDialog
1381 .findViewById(R.id.username_edit)).getText().toString();
1382 String password = ((TextView) mHttpAuthenticationDialog
1383 .findViewById(R.id.password_edit)).getText().toString();
1384 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1385 .getId();
1386 mHttpAuthenticationDialog.dismiss();
1387 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1388 name, password, focusId);
1389 }
1390 if (mFindDialog != null && mFindDialog.isShowing()) {
1391 mFindDialog.onConfigurationChanged(newConfig);
1392 }
1393 }
1394
1395 @Override public void onLowMemory() {
1396 super.onLowMemory();
1397 mTabControl.freeMemory();
1398 }
1399
Mike Reed7bfa63b2009-05-28 11:08:32 -04001400 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001401 if ((!mActivityInPause && !mPageStarted) ||
1402 (mActivityInPause && mPageStarted)) {
1403 CookieSyncManager.getInstance().startSync();
1404 WebView w = mTabControl.getCurrentWebView();
1405 if (w != null) {
1406 w.resumeTimers();
1407 }
1408 return true;
1409 } else {
1410 return false;
1411 }
1412 }
1413
Mike Reed7bfa63b2009-05-28 11:08:32 -04001414 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001415 if (mActivityInPause && !mPageStarted) {
1416 CookieSyncManager.getInstance().stopSync();
1417 WebView w = mTabControl.getCurrentWebView();
1418 if (w != null) {
1419 w.pauseTimers();
1420 }
1421 return true;
1422 } else {
1423 return false;
1424 }
1425 }
1426
1427 /*
1428 * This function is called when we are launching for the first time. We
1429 * are waiting for the login credentials before loading Google home
1430 * pages. This way the user will be logged in straight away.
1431 */
1432 private void waitForCredentials() {
1433 // Show a toast
1434 mCredsDlg = new ProgressDialog(this);
1435 mCredsDlg.setIndeterminate(true);
1436 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1437 // If the user cancels the operation, then cancel the Google
1438 // Credentials request.
1439 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1440 mCredsDlg.show();
1441
1442 // We set a timeout for the retrieval of credentials in onResume()
1443 // as that is when we have freed up some CPU time to get
1444 // the login credentials.
1445 }
1446
1447 /*
1448 * If we have received the credentials or we have timed out and we are
1449 * showing the credentials dialog, then it is time to move on.
1450 */
1451 private void resumeAfterCredentials() {
1452 if (mCredsDlg == null) {
1453 return;
1454 }
1455
1456 // Clear the toast
1457 if (mCredsDlg.isShowing()) {
1458 mCredsDlg.dismiss();
1459 }
1460 mCredsDlg = null;
1461
1462 // Clear any pending timeout
1463 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1464
1465 // Load the page
1466 WebView w = mTabControl.getCurrentWebView();
1467 if (w != null) {
1468 w.loadUrl(mSettings.getHomePage());
1469 }
1470
1471 // Update the settings, need to do this last as it can take a moment
1472 // to persist the settings. In the mean time we could be loading
1473 // content.
1474 mSettings.setLoginInitialized(this);
1475 }
1476
1477 // Open the icon database and retain all the icons for visited sites.
1478 private void retainIconsOnStartup() {
1479 final WebIconDatabase db = WebIconDatabase.getInstance();
1480 db.open(getDir("icons", 0).getPath());
1481 try {
1482 Cursor c = Browser.getAllBookmarks(mResolver);
1483 if (!c.moveToFirst()) {
1484 c.deactivate();
1485 return;
1486 }
1487 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1488 do {
1489 String url = c.getString(urlIndex);
1490 db.retainIconForPageUrl(url);
1491 } while (c.moveToNext());
1492 c.deactivate();
1493 } catch (IllegalStateException e) {
1494 Log.e(LOGTAG, "retainIconsOnStartup", e);
1495 }
1496 }
1497
1498 // Helper method for getting the top window.
1499 WebView getTopWindow() {
1500 return mTabControl.getCurrentTopWebView();
1501 }
1502
1503 @Override
1504 public boolean onCreateOptionsMenu(Menu menu) {
1505 super.onCreateOptionsMenu(menu);
1506
1507 MenuInflater inflater = getMenuInflater();
1508 inflater.inflate(R.menu.browser, menu);
1509 mMenu = menu;
1510 updateInLoadMenuItems();
1511 return true;
1512 }
1513
1514 /**
1515 * As the menu can be open when loading state changes
1516 * we must manually update the state of the stop/reload menu
1517 * item
1518 */
1519 private void updateInLoadMenuItems() {
1520 if (mMenu == null) {
1521 return;
1522 }
1523 MenuItem src = mInLoad ?
1524 mMenu.findItem(R.id.stop_menu_id):
1525 mMenu.findItem(R.id.reload_menu_id);
1526 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1527 dest.setIcon(src.getIcon());
1528 dest.setTitle(src.getTitle());
1529 }
1530
1531 @Override
1532 public boolean onContextItemSelected(MenuItem item) {
1533 // chording is not an issue with context menus, but we use the same
1534 // options selector, so set mCanChord to true so we can access them.
1535 mCanChord = true;
1536 int id = item.getItemId();
1537 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001538 if (null == webView) {
1539 return false;
1540 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001541 final HashMap hrefMap = new HashMap();
1542 hrefMap.put("webview", webView);
1543 final Message msg = mHandler.obtainMessage(
1544 FOCUS_NODE_HREF, id, 0, hrefMap);
1545 switch (id) {
1546 // -- Browser context menu
1547 case R.id.open_context_menu_id:
1548 case R.id.open_newtab_context_menu_id:
1549 case R.id.bookmark_context_menu_id:
1550 case R.id.save_link_context_menu_id:
1551 case R.id.share_link_context_menu_id:
1552 case R.id.copy_link_context_menu_id:
1553 webView.requestFocusNodeHref(msg);
1554 break;
1555
1556 default:
1557 // For other context menus
1558 return onOptionsItemSelected(item);
1559 }
1560 mCanChord = false;
1561 return true;
1562 }
1563
1564 private Bundle createGoogleSearchSourceBundle(String source) {
1565 Bundle bundle = new Bundle();
1566 bundle.putString(SearchManager.SOURCE, source);
1567 return bundle;
1568 }
1569
1570 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001571 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001572 */
1573 @Override
1574 public boolean onSearchRequested() {
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001575 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001576 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001577 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001578 return true;
1579 }
1580
1581 @Override
1582 public void startSearch(String initialQuery, boolean selectInitialQuery,
1583 Bundle appSearchData, boolean globalSearch) {
1584 if (appSearchData == null) {
1585 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1586 }
1587 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1588 }
1589
1590 @Override
1591 public boolean onOptionsItemSelected(MenuItem item) {
1592 if (!mCanChord) {
1593 // The user has already fired a shortcut with this hold down of the
1594 // menu key.
1595 return false;
1596 }
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001597 if (null == mTabOverview && null == getTopWindow()) {
1598 return false;
1599 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001600 if (mMenuIsDown) {
1601 // The shortcut action consumes the MENU. Even if it is still down,
1602 // it won't trigger the next shortcut action. In the case of the
1603 // shortcut action triggering a new activity, like Bookmarks, we
1604 // won't get onKeyUp for MENU. So it is important to reset it here.
1605 mMenuIsDown = false;
1606 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001607 switch (item.getItemId()) {
1608 // -- Main menu
Leon Scroggins64b80f32009-08-07 12:03:34 -04001609 case R.id.goto_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001610 bookmarksOrHistoryPicker(false);
1611 break;
1612
1613 case R.id.windows_menu_id:
1614 if (mTabControl.getTabCount() == 1) {
Leon Scroggins64b80f32009-08-07 12:03:34 -04001615 openTabAndShow(EMPTY_URL_DATA, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001616 } else {
1617 tabPicker(true, mTabControl.getCurrentIndex(), false);
1618 }
1619 break;
1620
1621 case R.id.stop_reload_menu_id:
1622 if (mInLoad) {
1623 stopLoading();
1624 } else {
1625 getTopWindow().reload();
1626 }
1627 break;
1628
1629 case R.id.back_menu_id:
1630 getTopWindow().goBack();
1631 break;
1632
1633 case R.id.forward_menu_id:
1634 getTopWindow().goForward();
1635 break;
1636
1637 case R.id.close_menu_id:
1638 // Close the subwindow if it exists.
1639 if (mTabControl.getCurrentSubWindow() != null) {
1640 dismissSubWindow(mTabControl.getCurrentTab());
1641 break;
1642 }
1643 final int currentIndex = mTabControl.getCurrentIndex();
1644 final TabControl.Tab parent =
1645 mTabControl.getCurrentTab().getParentTab();
1646 int indexToShow = -1;
1647 if (parent != null) {
1648 indexToShow = mTabControl.getTabIndex(parent);
1649 } else {
1650 // Get the last tab in the list. If it is the current tab,
1651 // subtract 1 more.
1652 indexToShow = mTabControl.getTabCount() - 1;
1653 if (currentIndex == indexToShow) {
1654 indexToShow--;
1655 }
1656 }
1657 switchTabs(currentIndex, indexToShow, true);
1658 break;
1659
1660 case R.id.homepage_menu_id:
1661 TabControl.Tab current = mTabControl.getCurrentTab();
1662 if (current != null) {
1663 dismissSubWindow(current);
1664 current.getWebView().loadUrl(mSettings.getHomePage());
1665 }
1666 break;
1667
1668 case R.id.preferences_menu_id:
1669 Intent intent = new Intent(this,
1670 BrowserPreferencesPage.class);
1671 startActivityForResult(intent, PREFERENCES_PAGE);
1672 break;
1673
1674 case R.id.find_menu_id:
1675 if (null == mFindDialog) {
1676 mFindDialog = new FindDialog(this);
1677 }
1678 mFindDialog.setWebView(getTopWindow());
1679 mFindDialog.show();
1680 mMenuState = EMPTY_MENU;
1681 break;
1682
1683 case R.id.select_text_id:
1684 getTopWindow().emulateShiftHeld();
1685 break;
1686 case R.id.page_info_menu_id:
1687 showPageInfo(mTabControl.getCurrentTab(), false);
1688 break;
1689
1690 case R.id.classic_history_menu_id:
1691 bookmarksOrHistoryPicker(true);
1692 break;
1693
1694 case R.id.share_page_menu_id:
1695 Browser.sendString(this, getTopWindow().getUrl());
1696 break;
1697
1698 case R.id.dump_nav_menu_id:
1699 getTopWindow().debugDump();
1700 break;
1701
1702 case R.id.zoom_in_menu_id:
1703 getTopWindow().zoomIn();
1704 break;
1705
1706 case R.id.zoom_out_menu_id:
1707 getTopWindow().zoomOut();
1708 break;
1709
1710 case R.id.view_downloads_menu_id:
1711 viewDownloads(null);
1712 break;
1713
1714 // -- Tab menu
1715 case R.id.view_tab_menu_id:
1716 if (mTabListener != null && mTabOverview != null) {
1717 int pos = mTabOverview.getContextMenuPosition(item);
1718 mTabOverview.setCurrentIndex(pos);
1719 mTabListener.onClick(pos);
1720 }
1721 break;
1722
1723 case R.id.remove_tab_menu_id:
1724 if (mTabListener != null && mTabOverview != null) {
1725 int pos = mTabOverview.getContextMenuPosition(item);
1726 mTabListener.remove(pos);
1727 }
1728 break;
1729
1730 case R.id.new_tab_menu_id:
1731 // No need to check for mTabOverview here since we are not
1732 // dependent on it for a position.
1733 if (mTabListener != null) {
1734 // If the overview happens to be non-null, make the "New
1735 // Tab" cell visible.
1736 if (mTabOverview != null) {
1737 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1738 }
1739 mTabListener.onClick(ImageGrid.NEW_TAB);
1740 }
1741 break;
1742
1743 case R.id.bookmark_tab_menu_id:
1744 if (mTabListener != null && mTabOverview != null) {
1745 int pos = mTabOverview.getContextMenuPosition(item);
1746 TabControl.Tab t = mTabControl.getTab(pos);
1747 // Since we called populatePickerData for all of the
1748 // tabs, getTitle and getUrl will return appropriate
1749 // values.
1750 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1751 t.getUrl());
1752 }
1753 break;
1754
1755 case R.id.history_tab_menu_id:
1756 bookmarksOrHistoryPicker(true);
1757 break;
1758
1759 case R.id.bookmarks_tab_menu_id:
1760 bookmarksOrHistoryPicker(false);
1761 break;
1762
1763 case R.id.properties_tab_menu_id:
1764 if (mTabListener != null && mTabOverview != null) {
1765 int pos = mTabOverview.getContextMenuPosition(item);
1766 showPageInfo(mTabControl.getTab(pos), false);
1767 }
1768 break;
1769
1770 case R.id.window_one_menu_id:
1771 case R.id.window_two_menu_id:
1772 case R.id.window_three_menu_id:
1773 case R.id.window_four_menu_id:
1774 case R.id.window_five_menu_id:
1775 case R.id.window_six_menu_id:
1776 case R.id.window_seven_menu_id:
1777 case R.id.window_eight_menu_id:
1778 {
1779 int menuid = item.getItemId();
1780 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1781 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1782 TabControl.Tab desiredTab = mTabControl.getTab(id);
1783 if (desiredTab != null &&
1784 desiredTab != mTabControl.getCurrentTab()) {
1785 switchTabs(mTabControl.getCurrentIndex(), id, false);
1786 }
1787 break;
1788 }
1789 }
1790 }
1791 break;
1792
1793 default:
1794 if (!super.onOptionsItemSelected(item)) {
1795 return false;
1796 }
1797 // Otherwise fall through.
1798 }
1799 mCanChord = false;
1800 return true;
1801 }
1802
1803 public void closeFind() {
1804 mMenuState = R.id.MAIN_MENU;
1805 }
1806
1807 @Override public boolean onPrepareOptionsMenu(Menu menu)
1808 {
1809 // This happens when the user begins to hold down the menu key, so
1810 // allow them to chord to get a shortcut.
1811 mCanChord = true;
1812 // Note: setVisible will decide whether an item is visible; while
1813 // setEnabled() will decide whether an item is enabled, which also means
1814 // whether the matching shortcut key will function.
1815 super.onPrepareOptionsMenu(menu);
1816 switch (mMenuState) {
1817 case R.id.TAB_MENU:
1818 if (mCurrentMenuState != mMenuState) {
1819 menu.setGroupVisible(R.id.MAIN_MENU, false);
1820 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1821 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1822 menu.setGroupVisible(R.id.TAB_MENU, true);
1823 menu.setGroupEnabled(R.id.TAB_MENU, true);
1824 }
1825 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1826 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1827 tab.setVisible(newT);
1828 tab.setEnabled(newT);
1829 break;
1830 case EMPTY_MENU:
1831 if (mCurrentMenuState != mMenuState) {
1832 menu.setGroupVisible(R.id.MAIN_MENU, false);
1833 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1834 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1835 menu.setGroupVisible(R.id.TAB_MENU, false);
1836 menu.setGroupEnabled(R.id.TAB_MENU, false);
1837 }
1838 break;
1839 default:
1840 if (mCurrentMenuState != mMenuState) {
1841 menu.setGroupVisible(R.id.MAIN_MENU, true);
1842 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1843 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1844 menu.setGroupVisible(R.id.TAB_MENU, false);
1845 menu.setGroupEnabled(R.id.TAB_MENU, false);
1846 }
1847 final WebView w = getTopWindow();
1848 boolean canGoBack = false;
1849 boolean canGoForward = false;
1850 boolean isHome = false;
1851 if (w != null) {
1852 canGoBack = w.canGoBack();
1853 canGoForward = w.canGoForward();
1854 isHome = mSettings.getHomePage().equals(w.getUrl());
1855 }
1856 final MenuItem back = menu.findItem(R.id.back_menu_id);
1857 back.setEnabled(canGoBack);
1858
1859 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1860 home.setEnabled(!isHome);
1861
1862 menu.findItem(R.id.forward_menu_id)
1863 .setEnabled(canGoForward);
1864
1865 // decide whether to show the share link option
1866 PackageManager pm = getPackageManager();
1867 Intent send = new Intent(Intent.ACTION_SEND);
1868 send.setType("text/plain");
1869 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1870 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1871
1872 // If there is only 1 window, the text will be "New window"
1873 final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1874 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1875 getString(R.string.view_tabs_condensed) :
1876 getString(R.string.tab_picker_new_tab));
1877
1878 boolean isNavDump = mSettings.isNavDump();
1879 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1880 nav.setVisible(isNavDump);
1881 nav.setEnabled(isNavDump);
1882 break;
1883 }
1884 mCurrentMenuState = mMenuState;
1885 return true;
1886 }
1887
1888 @Override
1889 public void onCreateContextMenu(ContextMenu menu, View v,
1890 ContextMenuInfo menuInfo) {
1891 WebView webview = (WebView) v;
1892 WebView.HitTestResult result = webview.getHitTestResult();
1893 if (result == null) {
1894 return;
1895 }
1896
1897 int type = result.getType();
1898 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1899 Log.w(LOGTAG,
1900 "We should not show context menu when nothing is touched");
1901 return;
1902 }
1903 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1904 // let TextView handles context menu
1905 return;
1906 }
1907
1908 // Note, http://b/issue?id=1106666 is requesting that
1909 // an inflated menu can be used again. This is not available
1910 // yet, so inflate each time (yuk!)
1911 MenuInflater inflater = getMenuInflater();
1912 inflater.inflate(R.menu.browsercontext, menu);
1913
1914 // Show the correct menu group
1915 String extra = result.getExtra();
1916 menu.setGroupVisible(R.id.PHONE_MENU,
1917 type == WebView.HitTestResult.PHONE_TYPE);
1918 menu.setGroupVisible(R.id.EMAIL_MENU,
1919 type == WebView.HitTestResult.EMAIL_TYPE);
1920 menu.setGroupVisible(R.id.GEO_MENU,
1921 type == WebView.HitTestResult.GEO_TYPE);
1922 menu.setGroupVisible(R.id.IMAGE_MENU,
1923 type == WebView.HitTestResult.IMAGE_TYPE
1924 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1925 menu.setGroupVisible(R.id.ANCHOR_MENU,
1926 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1927 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1928
1929 // Setup custom handling depending on the type
1930 switch (type) {
1931 case WebView.HitTestResult.PHONE_TYPE:
1932 menu.setHeaderTitle(Uri.decode(extra));
1933 menu.findItem(R.id.dial_context_menu_id).setIntent(
1934 new Intent(Intent.ACTION_VIEW, Uri
1935 .parse(WebView.SCHEME_TEL + extra)));
1936 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1937 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1938 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1939 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1940 addIntent);
1941 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1942 new Copy(extra));
1943 break;
1944
1945 case WebView.HitTestResult.EMAIL_TYPE:
1946 menu.setHeaderTitle(extra);
1947 menu.findItem(R.id.email_context_menu_id).setIntent(
1948 new Intent(Intent.ACTION_VIEW, Uri
1949 .parse(WebView.SCHEME_MAILTO + extra)));
1950 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1951 new Copy(extra));
1952 break;
1953
1954 case WebView.HitTestResult.GEO_TYPE:
1955 menu.setHeaderTitle(extra);
1956 menu.findItem(R.id.map_context_menu_id).setIntent(
1957 new Intent(Intent.ACTION_VIEW, Uri
1958 .parse(WebView.SCHEME_GEO
1959 + URLEncoder.encode(extra))));
1960 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1961 new Copy(extra));
1962 break;
1963
1964 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1965 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1966 TextView titleView = (TextView) LayoutInflater.from(this)
1967 .inflate(android.R.layout.browser_link_context_header,
1968 null);
1969 titleView.setText(extra);
1970 menu.setHeaderView(titleView);
1971 // decide whether to show the open link in new tab option
1972 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1973 mTabControl.getTabCount() < TabControl.MAX_TABS);
1974 PackageManager pm = getPackageManager();
1975 Intent send = new Intent(Intent.ACTION_SEND);
1976 send.setType("text/plain");
1977 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1978 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1979 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1980 break;
1981 }
1982 // otherwise fall through to handle image part
1983 case WebView.HitTestResult.IMAGE_TYPE:
1984 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1985 menu.setHeaderTitle(extra);
1986 }
1987 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1988 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1989 menu.findItem(R.id.download_context_menu_id).
1990 setOnMenuItemClickListener(new Download(extra));
1991 break;
1992
1993 default:
1994 Log.w(LOGTAG, "We should not get here.");
1995 break;
1996 }
1997 }
1998
The Android Open Source Project0c908882009-03-03 19:32:16 -08001999 // Attach the given tab to the content view.
2000 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01002001 // Attach the container that contains the main WebView and any other UI
2002 // associated with the tab.
2003 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01002004
2005 if (mShouldShowErrorConsole) {
2006 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
2007 if (errorConsole.numberOfErrors() == 0) {
2008 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2009 } else {
2010 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
2011 }
2012
2013 mErrorConsoleContainer.addView(errorConsole,
2014 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
2015 ViewGroup.LayoutParams.WRAP_CONTENT));
2016 }
2017
The Android Open Source Project0c908882009-03-03 19:32:16 -08002018 // Attach the sub window if necessary
2019 attachSubWindow(t);
2020 // Request focus on the top window.
2021 t.getTopWindow().requestFocus();
2022 }
2023
2024 // Attach a sub window to the main WebView of the given tab.
2025 private void attachSubWindow(TabControl.Tab t) {
2026 // If a sub window exists, attach it to the content view.
2027 final WebView subView = t.getSubWebView();
2028 if (subView != null) {
2029 final View container = t.getSubWebViewContainer();
2030 mContentView.addView(container, COVER_SCREEN_PARAMS);
2031 subView.requestFocus();
2032 }
2033 }
2034
2035 // Remove the given tab from the content view.
2036 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01002037 // Remove the container that contains the main WebView.
2038 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01002039
2040 if (mTabControl.getCurrentErrorConsole(false) != null) {
2041 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
2042 }
2043
The Android Open Source Project0c908882009-03-03 19:32:16 -08002044 // Remove the sub window if it exists.
2045 if (t.getSubWebView() != null) {
2046 mContentView.removeView(t.getSubWebViewContainer());
2047 }
2048 }
2049
2050 // Remove the sub window if it exists. Also called by TabControl when the
2051 // user clicks the 'X' to dismiss a sub window.
2052 /* package */ void dismissSubWindow(TabControl.Tab t) {
2053 final WebView mainView = t.getWebView();
2054 if (t.getSubWebView() != null) {
2055 // Remove the container view and request focus on the main WebView.
2056 mContentView.removeView(t.getSubWebViewContainer());
2057 mainView.requestFocus();
2058 // Tell the TabControl to dismiss the subwindow. This will destroy
2059 // the WebView.
2060 mTabControl.dismissSubWindow(t);
2061 }
2062 }
2063
2064 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
2065 private void sendAnimateFromOverview(final TabControl.Tab tab,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002066 final boolean newTab, final UrlData urlData, final int delay,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002067 final Message msg) {
2068 // Set the current tab.
2069 mTabControl.setCurrentTab(tab);
2070 // Attach the WebView so it will layout.
2071 attachTabToContentView(tab);
2072 // Set the view to invisibile for now.
2073 tab.getWebView().setVisibility(View.INVISIBLE);
2074 // If there is a sub window, make it invisible too.
2075 if (tab.getSubWebView() != null) {
2076 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
2077 }
2078 // Create our fake animating view.
2079 final AnimatingView view = new AnimatingView(this, tab);
2080 // Attach it to the view system and make in invisible so it will
2081 // layout but not flash white on the screen.
2082 mContentView.addView(view, COVER_SCREEN_PARAMS);
2083 view.setVisibility(View.INVISIBLE);
2084 // Send the animate message.
2085 final HashMap map = new HashMap();
2086 map.put("view", view);
2087 // Load the url after the AnimatingView has captured the picture. This
2088 // prevents any bad layout or bad scale from being used during
2089 // animation.
Leon Scroggins64b80f32009-08-07 12:03:34 -04002090 dismissSubWindow(tab);
2091 if (urlData.isEmpty()) {
2092 bookmarksOrHistoryPicker(false);
2093 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002094 urlData.loadIn(tab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095 }
2096 map.put("msg", msg);
2097 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2098 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
2099 // Increment the count to indicate that we are in an animation.
2100 mAnimationCount++;
2101 // Remove the listener so we don't get any more tab changes.
2102 mTabOverview.setListener(null);
2103 mTabListener = null;
2104 // Make the menu empty until the animation completes.
2105 mMenuState = EMPTY_MENU;
2106
2107 }
2108
2109 // 500ms animation with 800ms delay
Patrick Scott95d601f2009-06-11 10:06:46 -04002110 private static final int TAB_ANIMATION_DURATION = 200;
2111 private static final int TAB_OVERVIEW_DELAY = 500;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002112
2113 // Called by TabControl when a tab is requesting focus
2114 /* package */ void showTab(TabControl.Tab t) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002115 showTab(t, EMPTY_URL_DATA);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002116 }
2117
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002118 private void showTab(TabControl.Tab t, UrlData urlData) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 // Disallow focus change during a tab animation.
2120 if (mAnimationCount > 0) {
2121 return;
2122 }
2123 int delay = 0;
2124 if (mTabOverview == null) {
2125 // Add a delay so the tab overview can be shown before the second
2126 // animation begins.
2127 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2128 tabPicker(false, mTabControl.getTabIndex(t), false);
2129 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002130 sendAnimateFromOverview(t, false, urlData, delay, null);
2131 }
2132
2133 // A wrapper function of {@link #openTabAndShow(UrlData, Message, boolean, String)}
2134 // that accepts url as string.
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002135 private TabControl.Tab openTabAndShow(String url, final Message msg,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002136 boolean closeOnExit, String appId) {
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002137 return openTabAndShow(new UrlData(url), msg, closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 }
2139
2140 // This method does a ton of stuff. It will attempt to create a new tab
2141 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2142 // url isn't null, it will load the given url. If the tab overview is not
2143 // showing, it will animate to the tab overview, create a new tab and
2144 // animate away from it. After the animation completes, it will dispatch
2145 // the given Message. If the tab overview is already showing (i.e. this
2146 // method is called from TabListener.onClick(), the method will animate
2147 // away from the tab overview.
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002148 private TabControl.Tab openTabAndShow(UrlData urlData, final Message msg,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002149 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002150 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
2151 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
2152 if (newTab) {
2153 int delay = 0;
2154 // If the tab overview is up and there are animations, just load
2155 // the url.
2156 if (mTabOverview != null && mAnimationCount > 0) {
Leon Scroggins64b80f32009-08-07 12:03:34 -04002157 if (urlData.isEmpty()) {
2158 bookmarksOrHistoryPicker(false);
2159 } else {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 // We should not have a msg here since onCreateWindow
2161 // checks the animation count and every other caller passes
2162 // null.
2163 assert msg == null;
2164 // just dismiss the subwindow and load the given url.
2165 dismissSubWindow(currentTab);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002166 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002167 }
2168 } else {
2169 // show mTabOverview if it is not there.
2170 if (mTabOverview == null) {
2171 // We have to delay the animation from the tab picker by the
2172 // length of the tab animation. Add a delay so the tab
2173 // overview can be shown before the second animation begins.
2174 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2175 tabPicker(false, ImageGrid.NEW_TAB, false);
2176 }
2177 // Animate from the Tab overview after any animations have
2178 // finished.
Grace Klobac9181842009-04-14 08:53:22 -07002179 final TabControl.Tab tab = mTabControl.createNewTab(
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002180 closeOnExit, appId, urlData.mUrl);
Grace Klobaec7eb372009-06-16 13:45:56 -07002181 sendAnimateFromOverview(tab, true, urlData, delay, msg);
Grace Klobac9181842009-04-14 08:53:22 -07002182 return tab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002183 }
Leon Scroggins64b80f32009-08-07 12:03:34 -04002184 } else {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002185 // We should not have a msg here.
2186 assert msg == null;
2187 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002188 sendAnimateFromOverview(currentTab, false, urlData,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002189 TAB_OVERVIEW_DELAY, null);
2190 } else {
2191 // Get rid of the subwindow if it exists
2192 dismissSubWindow(currentTab);
Leon Scroggins64b80f32009-08-07 12:03:34 -04002193 if (!urlData.isEmpty()) {
2194 // Load the given url.
2195 urlData.loadIn(currentTab.getWebView());
2196 } else {
2197 bookmarksOrHistoryPicker(false);
2198 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002199 }
2200 }
Grace Klobac9181842009-04-14 08:53:22 -07002201 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002202 }
2203
2204 private Animation createTabAnimation(final AnimatingView view,
2205 final View cell, boolean scaleDown) {
2206 final AnimationSet set = new AnimationSet(true);
2207 final float scaleX = (float) cell.getWidth() / view.getWidth();
2208 final float scaleY = (float) cell.getHeight() / view.getHeight();
2209 if (scaleDown) {
2210 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
2211 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
2212 cell.getTop()));
2213 } else {
2214 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
2215 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
2216 cell.getTop(), 0));
2217 }
2218 set.setDuration(TAB_ANIMATION_DURATION);
2219 set.setInterpolator(new DecelerateInterpolator());
2220 return set;
2221 }
2222
2223 // Animate to the tab overview. currentIndex tells us which position to
2224 // animate to and newIndex is the position that should be selected after
2225 // the animation completes.
2226 // If remove is true, after the animation stops, a confirmation dialog will
2227 // be displayed to the user.
2228 private void animateToTabOverview(final int newIndex, final boolean remove,
2229 final AnimatingView view) {
2230 // Find the view in the ImageGrid allowing for the "New Tab" cell.
2231 int position = mTabControl.getTabIndex(view.mTab);
2232 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2233 position++;
2234 }
2235
2236 // Offset the tab position with the first visible position to get a
2237 // number between 0 and 3.
2238 position -= mTabOverview.getFirstVisiblePosition();
2239
2240 // Grab the view that we are going to animate to.
2241 final View v = mTabOverview.getChildAt(position);
2242
2243 final Animation.AnimationListener l =
2244 new Animation.AnimationListener() {
2245 public void onAnimationStart(Animation a) {
Patrick Scottd068f802009-06-22 11:46:06 -04002246 if (mTabOverview != null) {
2247 mTabOverview.requestFocus();
2248 // Clear the listener so we don't trigger a tab
2249 // selection.
2250 mTabOverview.setListener(null);
2251 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002252 }
2253 public void onAnimationRepeat(Animation a) {}
2254 public void onAnimationEnd(Animation a) {
2255 // We are no longer animating so decrement the count.
2256 mAnimationCount--;
2257 // Make the view GONE so that it will not draw between
2258 // now and when the Runnable is handled.
2259 view.setVisibility(View.GONE);
2260 // Post a runnable since we can't modify the view
2261 // hierarchy during this callback.
2262 mHandler.post(new Runnable() {
2263 public void run() {
2264 // Remove the AnimatingView.
2265 mContentView.removeView(view);
2266 if (mTabOverview != null) {
2267 // Make newIndex visible.
2268 mTabOverview.setCurrentIndex(newIndex);
2269 // Restore the listener.
2270 mTabOverview.setListener(mTabListener);
2271 // Change the menu to TAB_MENU if the
2272 // ImageGrid is interactive.
2273 if (mTabOverview.isLive()) {
2274 mMenuState = R.id.TAB_MENU;
2275 mTabOverview.requestFocus();
2276 }
2277 }
2278 // If a remove was requested, remove the tab.
2279 if (remove) {
2280 // During a remove, the current tab has
2281 // already changed. Remember the current one
2282 // here.
2283 final TabControl.Tab currentTab =
2284 mTabControl.getCurrentTab();
2285 // Remove the tab at newIndex from
2286 // TabControl and the tab overview.
2287 final TabControl.Tab tab =
2288 mTabControl.getTab(newIndex);
2289 mTabControl.removeTab(tab);
2290 // Restore the current tab.
2291 if (currentTab != tab) {
2292 mTabControl.setCurrentTab(currentTab);
2293 }
2294 if (mTabOverview != null) {
2295 mTabOverview.remove(newIndex);
2296 // Make the current tab visible.
2297 mTabOverview.setCurrentIndex(
2298 mTabControl.getCurrentIndex());
2299 }
2300 }
2301 }
2302 });
2303 }
2304 };
2305
2306 // Do an animation if there is a view to animate to.
2307 if (v != null) {
2308 // Create our animation
2309 final Animation anim = createTabAnimation(view, v, true);
2310 anim.setAnimationListener(l);
2311 // Start animating
2312 view.startAnimation(anim);
2313 } else {
2314 // If something goes wrong and we didn't find a view to animate to,
2315 // just do everything here.
2316 l.onAnimationStart(null);
2317 l.onAnimationEnd(null);
2318 }
2319 }
2320
2321 // Animate from the tab picker. The index supplied is the index to animate
2322 // from.
2323 private void animateFromTabOverview(final AnimatingView view,
2324 final boolean newTab, final Message msg) {
2325 // firstVisible is the first visible tab on the screen. This helps
2326 // to know which corner of the screen the selected tab is.
2327 int firstVisible = mTabOverview.getFirstVisiblePosition();
2328 // tabPosition is the 0-based index of of the tab being opened
2329 int tabPosition = mTabControl.getTabIndex(view.mTab);
2330 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2331 // Add one to make room for the "New Tab" cell.
2332 tabPosition++;
2333 }
2334 // If this is a new tab, animate from the "New Tab" cell.
2335 if (newTab) {
2336 tabPosition = 0;
2337 }
2338 // Location corresponds to the four corners of the screen.
2339 // A new tab or 0 is upper left, 0 for an old tab is upper
2340 // right, 1 is lower left, and 2 is lower right
2341 int location = tabPosition - firstVisible;
2342
2343 // Find the view at this location.
2344 final View v = mTabOverview.getChildAt(location);
2345
2346 // Wait until the animation completes to replace the AnimatingView.
2347 final Animation.AnimationListener l =
2348 new Animation.AnimationListener() {
2349 public void onAnimationStart(Animation a) {}
2350 public void onAnimationRepeat(Animation a) {}
2351 public void onAnimationEnd(Animation a) {
2352 mHandler.post(new Runnable() {
2353 public void run() {
2354 mContentView.removeView(view);
2355 // Dismiss the tab overview. If the cell at the
2356 // given location is null, set the fade
2357 // parameter to true.
2358 dismissTabOverview(v == null);
2359 TabControl.Tab t =
2360 mTabControl.getCurrentTab();
2361 mMenuState = R.id.MAIN_MENU;
2362 // Resume regular updates.
2363 t.getWebView().resumeTimers();
2364 // Dispatch the message after the animation
2365 // completes.
2366 if (msg != null) {
2367 msg.sendToTarget();
2368 }
2369 // The animation is done and the tab overview is
2370 // gone so allow key events and other animations
2371 // to begin.
2372 mAnimationCount--;
2373 // Reset all the title bar info.
2374 resetTitle();
2375 }
2376 });
2377 }
2378 };
2379
2380 if (v != null) {
2381 final Animation anim = createTabAnimation(view, v, false);
2382 // Set the listener and start animating
2383 anim.setAnimationListener(l);
2384 view.startAnimation(anim);
2385 // Make the view VISIBLE during the animation.
2386 view.setVisibility(View.VISIBLE);
2387 } else {
2388 // Go ahead and do all the cleanup.
2389 l.onAnimationEnd(null);
2390 }
2391 }
2392
2393 // Dismiss the tab overview applying a fade if needed.
2394 private void dismissTabOverview(final boolean fade) {
2395 if (fade) {
2396 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2397 anim.setDuration(500);
2398 anim.startNow();
2399 mTabOverview.startAnimation(anim);
2400 }
2401 // Just in case there was a problem with animating away from the tab
2402 // overview
2403 WebView current = mTabControl.getCurrentWebView();
2404 if (current != null) {
2405 current.setVisibility(View.VISIBLE);
2406 } else {
2407 Log.e(LOGTAG, "No current WebView in dismissTabOverview");
2408 }
2409 // Make the sub window container visible.
2410 if (mTabControl.getCurrentSubWindow() != null) {
2411 mTabControl.getCurrentTab().getSubWebViewContainer()
2412 .setVisibility(View.VISIBLE);
2413 }
2414 mContentView.removeView(mTabOverview);
Patrick Scott2ed6edb2009-04-22 10:07:45 -04002415 // Clear all the data for tab picker so next time it will be
2416 // recreated.
2417 mTabControl.wipeAllPickerData();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002418 mTabOverview.clear();
2419 mTabOverview = null;
2420 mTabListener = null;
2421 }
2422
Grace Klobac9181842009-04-14 08:53:22 -07002423 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002424 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002425 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002426 if (t != null) {
2427 t.getWebView().loadUrl(url);
2428 }
Grace Klobac9181842009-04-14 08:53:22 -07002429 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002430 } else {
Grace Klobac9181842009-04-14 08:53:22 -07002431 return openTabAndShow(url, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002432 }
2433 }
2434
2435 private class Copy implements OnMenuItemClickListener {
2436 private CharSequence mText;
2437
2438 public boolean onMenuItemClick(MenuItem item) {
2439 copy(mText);
2440 return true;
2441 }
2442
2443 public Copy(CharSequence toCopy) {
2444 mText = toCopy;
2445 }
2446 }
2447
2448 private class Download implements OnMenuItemClickListener {
2449 private String mText;
2450
2451 public boolean onMenuItemClick(MenuItem item) {
2452 onDownloadStartNoStream(mText, null, null, null, -1);
2453 return true;
2454 }
2455
2456 public Download(String toDownload) {
2457 mText = toDownload;
2458 }
2459 }
2460
2461 private void copy(CharSequence text) {
2462 try {
2463 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2464 if (clip != null) {
2465 clip.setClipboardText(text);
2466 }
2467 } catch (android.os.RemoteException e) {
2468 Log.e(LOGTAG, "Copy failed", e);
2469 }
2470 }
2471
2472 /**
2473 * Resets the browser title-view to whatever it must be (for example, if we
2474 * load a page from history).
2475 */
2476 private void resetTitle() {
2477 resetLockIcon();
2478 resetTitleIconAndProgress();
2479 }
2480
2481 /**
2482 * Resets the browser title-view to whatever it must be
2483 * (for example, if we had a loading error)
2484 * When we have a new page, we call resetTitle, when we
2485 * have to reset the titlebar to whatever it used to be
2486 * (for example, if the user chose to stop loading), we
2487 * call resetTitleAndRevertLockIcon.
2488 */
2489 /* package */ void resetTitleAndRevertLockIcon() {
2490 revertLockIcon();
2491 resetTitleIconAndProgress();
2492 }
2493
2494 /**
2495 * Reset the title, favicon, and progress.
2496 */
2497 private void resetTitleIconAndProgress() {
2498 WebView current = mTabControl.getCurrentWebView();
2499 if (current == null) {
2500 return;
2501 }
2502 resetTitleAndIcon(current);
2503 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002504 mWebChromeClient.onProgressChanged(current, progress);
2505 }
2506
2507 // Reset the title and the icon based on the given item.
2508 private void resetTitleAndIcon(WebView view) {
2509 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2510 if (item != null) {
2511 setUrlTitle(item.getUrl(), item.getTitle());
2512 setFavicon(item.getFavicon());
2513 } else {
2514 setUrlTitle(null, null);
2515 setFavicon(null);
2516 }
2517 }
2518
2519 /**
2520 * Sets a title composed of the URL and the title string.
2521 * @param url The URL of the site being loaded.
2522 * @param title The title of the site being loaded.
2523 */
2524 private void setUrlTitle(String url, String title) {
2525 mUrl = url;
2526 mTitle = title;
2527
2528 // While the tab overview is animating or being shown, block changes
2529 // to the title.
2530 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04002531 if (CUSTOM_BROWSER_BAR) {
2532 mTitleBar.setTitleAndUrl(title, url);
2533 } else {
2534 setTitle(buildUrlTitle(url, title));
2535 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002536 }
2537 }
2538
2539 /**
2540 * Builds and returns the page title, which is some
2541 * combination of the page URL and title.
2542 * @param url The URL of the site being loaded.
2543 * @param title The title of the site being loaded.
2544 * @return The page title.
2545 */
2546 private String buildUrlTitle(String url, String title) {
2547 String urlTitle = "";
2548
2549 if (url != null) {
2550 String titleUrl = buildTitleUrl(url);
2551
2552 if (title != null && 0 < title.length()) {
2553 if (titleUrl != null && 0 < titleUrl.length()) {
2554 urlTitle = titleUrl + ": " + title;
2555 } else {
2556 urlTitle = title;
2557 }
2558 } else {
2559 if (titleUrl != null) {
2560 urlTitle = titleUrl;
2561 }
2562 }
2563 }
2564
2565 return urlTitle;
2566 }
2567
2568 /**
2569 * @param url The URL to build a title version of the URL from.
2570 * @return The title version of the URL or null if fails.
2571 * The title version of the URL can be either the URL hostname,
2572 * or the hostname with an "https://" prefix (for secure URLs),
2573 * or an empty string if, for example, the URL in question is a
2574 * file:// URL with no hostname.
2575 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002576 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002577 String titleUrl = null;
2578
2579 if (url != null) {
2580 try {
2581 // parse the url string
2582 URL urlObj = new URL(url);
2583 if (urlObj != null) {
2584 titleUrl = "";
2585
2586 String protocol = urlObj.getProtocol();
2587 String host = urlObj.getHost();
2588
2589 if (host != null && 0 < host.length()) {
2590 titleUrl = host;
2591 if (protocol != null) {
2592 // if a secure site, add an "https://" prefix!
2593 if (protocol.equalsIgnoreCase("https")) {
2594 titleUrl = protocol + "://" + host;
2595 }
2596 }
2597 }
2598 }
2599 } catch (MalformedURLException e) {}
2600 }
2601
2602 return titleUrl;
2603 }
2604
2605 // Set the favicon in the title bar.
2606 private void setFavicon(Bitmap icon) {
2607 // While the tab overview is animating or being shown, block changes to
2608 // the favicon.
2609 if (mAnimationCount > 0 || mTabOverview != null) {
2610 return;
2611 }
Leon Scroggins81db3662009-06-04 17:45:11 -04002612 if (CUSTOM_BROWSER_BAR) {
2613 Drawable[] array = new Drawable[3];
2614 array[0] = new PaintDrawable(Color.BLACK);
2615 PaintDrawable p = new PaintDrawable(Color.WHITE);
2616 array[1] = p;
2617 if (icon == null) {
2618 array[2] = mGenericFavicon;
2619 } else {
2620 array[2] = new BitmapDrawable(icon);
2621 }
2622 LayerDrawable d = new LayerDrawable(array);
2623 d.setLayerInset(1, 1, 1, 1, 1);
2624 d.setLayerInset(2, 2, 2, 2, 2);
2625 mTitleBar.setFavicon(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002626 } else {
Leon Scroggins81db3662009-06-04 17:45:11 -04002627 Drawable[] array = new Drawable[2];
2628 PaintDrawable p = new PaintDrawable(Color.WHITE);
2629 p.setCornerRadius(3f);
2630 array[0] = p;
2631 if (icon == null) {
2632 array[1] = mGenericFavicon;
2633 } else {
2634 array[1] = new BitmapDrawable(icon);
2635 }
2636 LayerDrawable d = new LayerDrawable(array);
2637 d.setLayerInset(1, 2, 2, 2, 2);
2638 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002639 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002640 }
2641
2642 /**
2643 * Saves the current lock-icon state before resetting
2644 * the lock icon. If we have an error, we may need to
2645 * roll back to the previous state.
2646 */
2647 private void saveLockIcon() {
2648 mPrevLockType = mLockIconType;
2649 }
2650
2651 /**
2652 * Reverts the lock-icon state to the last saved state,
2653 * for example, if we had an error, and need to cancel
2654 * the load.
2655 */
2656 private void revertLockIcon() {
2657 mLockIconType = mPrevLockType;
2658
Dave Bort31a6d1c2009-04-13 15:56:49 -07002659 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002660 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2661 " revert lock icon to " + mLockIconType);
2662 }
2663
2664 updateLockIconImage(mLockIconType);
2665 }
2666
2667 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
2668 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2669 // Animate to the tab picker, remove the current tab, then
2670 // animate away from the tab picker to the parent WebView.
2671 tabPicker(false, indexFrom, remove);
2672 // Change to the parent tab
2673 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2674 if (tab != null) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002675 sendAnimateFromOverview(tab, false, EMPTY_URL_DATA, delay, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002676 } else {
2677 // Increment this here so that no other animations can happen in
2678 // between the end of the tab picker transition and the beginning
2679 // of openTabAndShow. This has a matching decrement in the handler
2680 // of OPEN_TAB_AND_SHOW.
2681 mAnimationCount++;
2682 // Send a message to open a new tab.
2683 mHandler.sendMessageDelayed(
2684 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
Leon Scroggins64b80f32009-08-07 12:03:34 -04002685 null), delay);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002686 }
2687 }
2688
2689 private void goBackOnePageOrQuit() {
2690 TabControl.Tab current = mTabControl.getCurrentTab();
2691 if (current == null) {
2692 /*
2693 * Instead of finishing the activity, simply push this to the back
2694 * of the stack and let ActivityManager to choose the foreground
2695 * activity. As BrowserActivity is singleTask, it will be always the
2696 * root of the task. So we can use either true or false for
2697 * moveTaskToBack().
2698 */
2699 moveTaskToBack(true);
2700 }
2701 WebView w = current.getWebView();
2702 if (w.canGoBack()) {
2703 w.goBack();
2704 } else {
2705 // Check to see if we are closing a window that was created by
2706 // another window. If so, we switch back to that window.
2707 TabControl.Tab parent = current.getParentTab();
2708 if (parent != null) {
2709 switchTabs(mTabControl.getCurrentIndex(),
2710 mTabControl.getTabIndex(parent), true);
2711 } else {
2712 if (current.closeOnExit()) {
2713 if (mTabControl.getTabCount() == 1) {
2714 finish();
2715 return;
2716 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002717 // call pauseWebViewTimers() now, we won't be able to call
2718 // it in onPause() as the WebView won't be valid.
2719 pauseWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002720 removeTabFromContentView(current);
2721 mTabControl.removeTab(current);
2722 }
2723 /*
2724 * Instead of finishing the activity, simply push this to the back
2725 * of the stack and let ActivityManager to choose the foreground
2726 * activity. As BrowserActivity is singleTask, it will be always the
2727 * root of the task. So we can use either true or false for
2728 * moveTaskToBack().
2729 */
2730 moveTaskToBack(true);
2731 }
2732 }
2733 }
2734
2735 public KeyTracker.State onKeyTracker(int keyCode,
2736 KeyEvent event,
2737 KeyTracker.Stage stage,
2738 int duration) {
2739 // if onKeyTracker() is called after activity onStop()
2740 // because of accumulated key events,
2741 // we should ignore it as browser is not active any more.
2742 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002743 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002744 return KeyTracker.State.NOT_TRACKING;
2745
2746 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002747 // Check if a custom view is currently showing and, if it is, hide it.
2748 if (mCustomView != null) {
2749 mWebChromeClient.onHideCustomView();
2750 return KeyTracker.State.DONE_TRACKING;
2751 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002752 // During animations, block the back key so that other animations
2753 // are not triggered and so that we don't end up destroying all the
2754 // WebViews before finishing the animation.
2755 if (mAnimationCount > 0) {
2756 return KeyTracker.State.DONE_TRACKING;
2757 }
2758 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2759 bookmarksOrHistoryPicker(true);
2760 return KeyTracker.State.DONE_TRACKING;
2761 } else if (stage == KeyTracker.Stage.UP) {
2762 // FIXME: Currently, we do not have a notion of the
2763 // history picker for the subwindow, but maybe we
2764 // should?
2765 WebView subwindow = mTabControl.getCurrentSubWindow();
2766 if (subwindow != null) {
2767 if (subwindow.canGoBack()) {
2768 subwindow.goBack();
2769 } else {
2770 dismissSubWindow(mTabControl.getCurrentTab());
2771 }
2772 } else {
2773 goBackOnePageOrQuit();
2774 }
2775 return KeyTracker.State.DONE_TRACKING;
2776 }
2777 return KeyTracker.State.KEEP_TRACKING;
2778 }
2779 return KeyTracker.State.NOT_TRACKING;
2780 }
2781
2782 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2783 if (keyCode == KeyEvent.KEYCODE_MENU) {
2784 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002785 } else if (mMenuIsDown) {
2786 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2787 // still down, we don't want to trigger the search. Pretend to
2788 // consume the key and do nothing.
2789 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002790 }
2791 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2792 if (!handled) {
2793 switch (keyCode) {
2794 case KeyEvent.KEYCODE_SPACE:
2795 if (event.isShiftPressed()) {
2796 getTopWindow().pageUp(false);
2797 } else {
2798 getTopWindow().pageDown(false);
2799 }
2800 handled = true;
2801 break;
2802
2803 default:
2804 break;
2805 }
2806 }
2807 return handled || super.onKeyDown(keyCode, event);
2808 }
2809
2810 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2811 if (keyCode == KeyEvent.KEYCODE_MENU) {
2812 mMenuIsDown = false;
2813 }
2814 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2815 }
2816
2817 private void stopLoading() {
2818 resetTitleAndRevertLockIcon();
2819 WebView w = getTopWindow();
2820 w.stopLoading();
2821 mWebViewClient.onPageFinished(w, w.getUrl());
2822
2823 cancelStopToast();
2824 mStopToast = Toast
2825 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2826 mStopToast.show();
2827 }
2828
2829 private void cancelStopToast() {
2830 if (mStopToast != null) {
2831 mStopToast.cancel();
2832 mStopToast = null;
2833 }
2834 }
2835
2836 // called by a non-UI thread to post the message
2837 public void postMessage(int what, int arg1, int arg2, Object obj) {
2838 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2839 }
2840
2841 // public message ids
2842 public final static int LOAD_URL = 1001;
2843 public final static int STOP_LOAD = 1002;
2844
2845 // Message Ids
2846 private static final int FOCUS_NODE_HREF = 102;
2847 private static final int CANCEL_CREDS_REQUEST = 103;
2848 private static final int ANIMATE_FROM_OVERVIEW = 104;
2849 private static final int ANIMATE_TO_OVERVIEW = 105;
2850 private static final int OPEN_TAB_AND_SHOW = 106;
Grace Kloba92c18a52009-07-31 23:48:32 -07002851 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002852
2853 // Private handler for handling javascript and saving passwords
2854 private Handler mHandler = new Handler() {
2855
2856 public void handleMessage(Message msg) {
2857 switch (msg.what) {
2858 case ANIMATE_FROM_OVERVIEW:
2859 final HashMap map = (HashMap) msg.obj;
2860 animateFromTabOverview((AnimatingView) map.get("view"),
2861 msg.arg1 == 1, (Message) map.get("msg"));
2862 break;
2863
2864 case ANIMATE_TO_OVERVIEW:
2865 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2866 (AnimatingView) msg.obj);
2867 break;
2868
2869 case OPEN_TAB_AND_SHOW:
2870 // Decrement mAnimationCount before openTabAndShow because
2871 // the method relies on the value being 0 to start the next
2872 // animation.
2873 mAnimationCount--;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002874 openTabAndShow((String) msg.obj, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002875 break;
2876
2877 case FOCUS_NODE_HREF:
2878 String url = (String) msg.getData().get("url");
2879 if (url == null || url.length() == 0) {
2880 break;
2881 }
2882 HashMap focusNodeMap = (HashMap) msg.obj;
2883 WebView view = (WebView) focusNodeMap.get("webview");
2884 // Only apply the action if the top window did not change.
2885 if (getTopWindow() != view) {
2886 break;
2887 }
2888 switch (msg.arg1) {
2889 case R.id.open_context_menu_id:
2890 case R.id.view_image_context_menu_id:
2891 loadURL(getTopWindow(), url);
2892 break;
2893 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002894 final TabControl.Tab parent = mTabControl
2895 .getCurrentTab();
2896 final TabControl.Tab newTab = openTab(url);
2897 if (newTab != parent) {
2898 parent.addChildTab(newTab);
2899 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002900 break;
2901 case R.id.bookmark_context_menu_id:
2902 Intent intent = new Intent(BrowserActivity.this,
2903 AddBookmarkPage.class);
2904 intent.putExtra("url", url);
2905 startActivity(intent);
2906 break;
2907 case R.id.share_link_context_menu_id:
2908 Browser.sendString(BrowserActivity.this, url);
2909 break;
2910 case R.id.copy_link_context_menu_id:
2911 copy(url);
2912 break;
2913 case R.id.save_link_context_menu_id:
2914 case R.id.download_context_menu_id:
2915 onDownloadStartNoStream(url, null, null, null, -1);
2916 break;
2917 }
2918 break;
2919
2920 case LOAD_URL:
2921 loadURL(getTopWindow(), (String) msg.obj);
2922 break;
2923
2924 case STOP_LOAD:
2925 stopLoading();
2926 break;
2927
2928 case CANCEL_CREDS_REQUEST:
2929 resumeAfterCredentials();
2930 break;
2931
The Android Open Source Project0c908882009-03-03 19:32:16 -08002932 case RELEASE_WAKELOCK:
2933 if (mWakeLock.isHeld()) {
2934 mWakeLock.release();
2935 }
2936 break;
2937 }
2938 }
2939 };
2940
Leon Scroggins89c6d362009-07-15 16:54:37 -04002941 private void updateScreenshot(WebView view) {
2942 // If this is a bookmarked site, add a screenshot to the database.
2943 // FIXME: When should we update? Every time?
2944 // FIXME: Would like to make sure there is actually something to
2945 // draw, but the API for that (WebViewCore.pictureReady()) is not
2946 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002947 ContentResolver cr = getContentResolver();
2948 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002949 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002950 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002951 boolean succeed = c.moveToFirst();
2952 ContentValues values = null;
2953 while (succeed) {
2954 if (values == null) {
2955 final ByteArrayOutputStream os
2956 = new ByteArrayOutputStream();
2957 Picture thumbnail = view.capturePicture();
2958 // Keep width and height in sync with BrowserBookmarksPage
2959 // and bookmark_thumb
2960 Bitmap bm = Bitmap.createBitmap(100, 80,
2961 Bitmap.Config.ARGB_4444);
2962 Canvas canvas = new Canvas(bm);
2963 // May need to tweak these values to determine what is the
2964 // best scale factor
2965 canvas.scale(.5f, .5f);
2966 thumbnail.draw(canvas);
2967 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2968 values = new ContentValues();
2969 values.put(Browser.BookmarkColumns.THUMBNAIL,
2970 os.toByteArray());
2971 }
2972 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2973 c.getInt(0)), values, null, null);
2974 succeed = c.moveToNext();
2975 }
2976 c.close();
2977 }
2978 }
2979
The Android Open Source Project0c908882009-03-03 19:32:16 -08002980 // -------------------------------------------------------------------------
2981 // WebViewClient implementation.
2982 //-------------------------------------------------------------------------
2983
2984 // Use in overrideUrlLoading
2985 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2986 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2987 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2988 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2989
2990 /* package */ WebViewClient getWebViewClient() {
2991 return mWebViewClient;
2992 }
2993
Patrick Scott3918d442009-08-04 13:22:29 -04002994 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002995 if (icon != null) {
2996 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002997 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002998 }
2999 setFavicon(icon);
3000 }
3001
3002 private final WebViewClient mWebViewClient = new WebViewClient() {
3003 @Override
3004 public void onPageStarted(WebView view, String url, Bitmap favicon) {
3005 resetLockIcon(url);
3006 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01003007
3008 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
3009 if (errorConsole != null) {
3010 errorConsole.clearErrorMessages();
3011 if (mShouldShowErrorConsole) {
3012 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3013 }
3014 }
3015
The Android Open Source Project0c908882009-03-03 19:32:16 -08003016 // Call updateIcon instead of setFavicon so the bookmark
3017 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04003018 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003019
3020 if (mSettings.isTracing() == true) {
3021 // FIXME: we should save the trace file somewhere other than data.
3022 // I can't use "/tmp" as it competes for system memory.
3023 File file = getDir("browserTrace", 0);
3024 String baseDir = file.getPath();
3025 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
3026 String host;
3027 try {
3028 WebAddress uri = new WebAddress(url);
3029 host = uri.mHost;
3030 } catch (android.net.ParseException ex) {
3031 host = "unknown_host";
3032 }
3033 host = host.replace('.', '_');
3034 baseDir = baseDir + host;
3035 file = new File(baseDir+".data");
3036 if (file.exists() == true) {
3037 file.delete();
3038 }
3039 file = new File(baseDir+".key");
3040 if (file.exists() == true) {
3041 file.delete();
3042 }
3043 mInTrace = true;
3044 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
3045 }
3046
3047 // Performance probe
3048 if (false) {
3049 mStart = SystemClock.uptimeMillis();
3050 mProcessStart = Process.getElapsedCpuTime();
3051 long[] sysCpu = new long[7];
3052 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
3053 sysCpu, null)) {
3054 mUserStart = sysCpu[0] + sysCpu[1];
3055 mSystemStart = sysCpu[2];
3056 mIdleStart = sysCpu[3];
3057 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
3058 }
3059 mUiStart = SystemClock.currentThreadTimeMillis();
3060 }
3061
3062 if (!mPageStarted) {
3063 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04003064 // if onResume() has been called, resumeWebViewTimers() does
3065 // nothing.
3066 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067 }
3068
3069 // reset sync timer to avoid sync starts during loading a page
3070 CookieSyncManager.getInstance().resetSync();
3071
3072 mInLoad = true;
3073 updateInLoadMenuItems();
3074 if (!mIsNetworkUp) {
3075 if ( mAlertDialog == null) {
3076 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
3077 .setTitle(R.string.loadSuspendedTitle)
3078 .setMessage(R.string.loadSuspended)
3079 .setPositiveButton(R.string.ok, null)
3080 .show();
3081 }
3082 if (view != null) {
3083 view.setNetworkAvailable(false);
3084 }
3085 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003086 }
3087
3088 @Override
3089 public void onPageFinished(WebView view, String url) {
3090 // Reset the title and icon in case we stopped a provisional
3091 // load.
3092 resetTitleAndIcon(view);
3093
3094 // Update the lock icon image only once we are done loading
3095 updateLockIconImage(mLockIconType);
Leon Scroggins89c6d362009-07-15 16:54:37 -04003096 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04003097
The Android Open Source Project0c908882009-03-03 19:32:16 -08003098 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003099 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003100 long[] sysCpu = new long[7];
3101 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
3102 sysCpu, null)) {
3103 String uiInfo = "UI thread used "
3104 + (SystemClock.currentThreadTimeMillis() - mUiStart)
3105 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07003106 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003107 Log.d(LOGTAG, uiInfo);
3108 }
3109 //The string that gets written to the log
3110 String performanceString = "It took total "
3111 + (SystemClock.uptimeMillis() - mStart)
3112 + " ms clock time to load the page."
3113 + "\nbrowser process used "
3114 + (Process.getElapsedCpuTime() - mProcessStart)
3115 + " ms, user processes used "
3116 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
3117 + " ms, kernel used "
3118 + (sysCpu[2] - mSystemStart) * 10
3119 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
3120 + " ms and irq took "
3121 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
3122 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003123 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003124 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
3125 }
3126 if (url != null) {
3127 // strip the url to maintain consistency
3128 String newUrl = new String(url);
3129 if (newUrl.startsWith("http://www.")) {
3130 newUrl = newUrl.substring(11);
3131 } else if (newUrl.startsWith("http://")) {
3132 newUrl = newUrl.substring(7);
3133 } else if (newUrl.startsWith("https://www.")) {
3134 newUrl = newUrl.substring(12);
3135 } else if (newUrl.startsWith("https://")) {
3136 newUrl = newUrl.substring(8);
3137 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07003138 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003139 Log.d(LOGTAG, newUrl + " loaded");
3140 }
3141 /*
3142 if (sWhiteList.contains(newUrl)) {
3143 // The string that gets pushed to the statistcs
3144 // service
3145 performanceString = performanceString
3146 + "\nWebpage: "
3147 + newUrl
3148 + "\nCarrier: "
3149 + android.os.SystemProperties
3150 .get("gsm.sim.operator.alpha");
3151 if (mWebView != null
3152 && mWebView.getContext() != null
3153 && mWebView.getContext().getSystemService(
3154 Context.CONNECTIVITY_SERVICE) != null) {
3155 ConnectivityManager cManager =
3156 (ConnectivityManager) mWebView
3157 .getContext().getSystemService(
3158 Context.CONNECTIVITY_SERVICE);
3159 NetworkInfo nInfo = cManager
3160 .getActiveNetworkInfo();
3161 if (nInfo != null) {
3162 performanceString = performanceString
3163 + "\nNetwork Type: "
3164 + nInfo.getType().toString();
3165 }
3166 }
3167 Checkin.logEvent(mResolver,
3168 Checkin.Events.Tag.WEBPAGE_LOAD,
3169 performanceString);
3170 Log.w(LOGTAG, "pushed to the statistics service");
3171 }
3172 */
3173 }
3174 }
3175 }
3176
3177 if (mInTrace) {
3178 mInTrace = false;
3179 Debug.stopMethodTracing();
3180 }
3181
3182 if (mPageStarted) {
3183 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04003184 // pauseWebViewTimers() will do nothing and return false if
3185 // onPause() is not called yet.
3186 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003187 if (mWakeLock.isHeld()) {
3188 mHandler.removeMessages(RELEASE_WAKELOCK);
3189 mWakeLock.release();
3190 }
3191 }
3192 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003193 }
3194
3195 // return true if want to hijack the url to let another app to handle it
3196 @Override
3197 public boolean shouldOverrideUrlLoading(WebView view, String url) {
3198 if (url.startsWith(SCHEME_WTAI)) {
3199 // wtai://wp/mc;number
3200 // number=string(phone-number)
3201 if (url.startsWith(SCHEME_WTAI_MC)) {
3202 Intent intent = new Intent(Intent.ACTION_VIEW,
3203 Uri.parse(WebView.SCHEME_TEL +
3204 url.substring(SCHEME_WTAI_MC.length())));
3205 startActivity(intent);
3206 return true;
3207 }
3208 // wtai://wp/sd;dtmf
3209 // dtmf=string(dialstring)
3210 if (url.startsWith(SCHEME_WTAI_SD)) {
3211 // TODO
3212 // only send when there is active voice connection
3213 return false;
3214 }
3215 // wtai://wp/ap;number;name
3216 // number=string(phone-number)
3217 // name=string
3218 if (url.startsWith(SCHEME_WTAI_AP)) {
3219 // TODO
3220 return false;
3221 }
3222 }
3223
Dianne Hackborn99189432009-06-17 18:06:18 -07003224 // The "about:" schemes are internal to the browser; don't
3225 // want these to be dispatched to other apps.
3226 if (url.startsWith("about:")) {
3227 return false;
3228 }
Ben Murdochbff2d602009-07-01 20:19:05 +01003229
Dianne Hackborn99189432009-06-17 18:06:18 -07003230 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01003231
Dianne Hackborn99189432009-06-17 18:06:18 -07003232 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003233 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07003234 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
3235 } catch (URISyntaxException ex) {
3236 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003237 return false;
3238 }
3239
Grace Kloba5b078b52009-06-24 20:23:41 -07003240 // check whether the intent can be resolved. If not, we will see
3241 // whether we can download it from the Market.
3242 if (getPackageManager().resolveActivity(intent, 0) == null) {
3243 String packagename = intent.getPackage();
3244 if (packagename != null) {
3245 intent = new Intent(Intent.ACTION_VIEW, Uri
3246 .parse("market://search?q=pname:" + packagename));
3247 intent.addCategory(Intent.CATEGORY_BROWSABLE);
3248 startActivity(intent);
3249 return true;
3250 } else {
3251 return false;
3252 }
3253 }
3254
Dianne Hackborn99189432009-06-17 18:06:18 -07003255 // sanitize the Intent, ensuring web pages can not bypass browser
3256 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08003257 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07003258 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003259 try {
3260 if (startActivityIfNeeded(intent, -1)) {
3261 return true;
3262 }
3263 } catch (ActivityNotFoundException ex) {
3264 // ignore the error. If no application can handle the URL,
3265 // eg about:blank, assume the browser can handle it.
3266 }
3267
3268 if (mMenuIsDown) {
3269 openTab(url);
3270 closeOptionsMenu();
3271 return true;
3272 }
3273
3274 return false;
3275 }
3276
3277 /**
3278 * Updates the lock icon. This method is called when we discover another
3279 * resource to be loaded for this page (for example, javascript). While
3280 * we update the icon type, we do not update the lock icon itself until
3281 * we are done loading, it is slightly more secure this way.
3282 */
3283 @Override
3284 public void onLoadResource(WebView view, String url) {
3285 if (url != null && url.length() > 0) {
3286 // It is only if the page claims to be secure
3287 // that we may have to update the lock:
3288 if (mLockIconType == LOCK_ICON_SECURE) {
3289 // If NOT a 'safe' url, change the lock to mixed content!
3290 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
3291 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003292 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003293 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3294 " updated lock icon to " + mLockIconType + " due to " + url);
3295 }
3296 }
3297 }
3298 }
3299 }
3300
3301 /**
3302 * Show the dialog, asking the user if they would like to continue after
3303 * an excessive number of HTTP redirects.
3304 */
3305 @Override
3306 public void onTooManyRedirects(WebView view, final Message cancelMsg,
3307 final Message continueMsg) {
3308 new AlertDialog.Builder(BrowserActivity.this)
3309 .setTitle(R.string.browserFrameRedirect)
3310 .setMessage(R.string.browserFrame307Post)
3311 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3312 public void onClick(DialogInterface dialog, int which) {
3313 continueMsg.sendToTarget();
3314 }})
3315 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3316 public void onClick(DialogInterface dialog, int which) {
3317 cancelMsg.sendToTarget();
3318 }})
3319 .setOnCancelListener(new OnCancelListener() {
3320 public void onCancel(DialogInterface dialog) {
3321 cancelMsg.sendToTarget();
3322 }})
3323 .show();
3324 }
3325
Patrick Scott37911c72009-03-24 18:02:58 -07003326 // Container class for the next error dialog that needs to be
3327 // displayed.
3328 class ErrorDialog {
3329 public final int mTitle;
3330 public final String mDescription;
3331 public final int mError;
3332 ErrorDialog(int title, String desc, int error) {
3333 mTitle = title;
3334 mDescription = desc;
3335 mError = error;
3336 }
3337 };
3338
3339 private void processNextError() {
3340 if (mQueuedErrors == null) {
3341 return;
3342 }
3343 // The first one is currently displayed so just remove it.
3344 mQueuedErrors.removeFirst();
3345 if (mQueuedErrors.size() == 0) {
3346 mQueuedErrors = null;
3347 return;
3348 }
3349 showError(mQueuedErrors.getFirst());
3350 }
3351
3352 private DialogInterface.OnDismissListener mDialogListener =
3353 new DialogInterface.OnDismissListener() {
3354 public void onDismiss(DialogInterface d) {
3355 processNextError();
3356 }
3357 };
3358 private LinkedList<ErrorDialog> mQueuedErrors;
3359
3360 private void queueError(int err, String desc) {
3361 if (mQueuedErrors == null) {
3362 mQueuedErrors = new LinkedList<ErrorDialog>();
3363 }
3364 for (ErrorDialog d : mQueuedErrors) {
3365 if (d.mError == err) {
3366 // Already saw a similar error, ignore the new one.
3367 return;
3368 }
3369 }
3370 ErrorDialog errDialog = new ErrorDialog(
3371 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3372 R.string.browserFrameFileErrorLabel :
3373 R.string.browserFrameNetworkErrorLabel,
3374 desc, err);
3375 mQueuedErrors.addLast(errDialog);
3376
3377 // Show the dialog now if the queue was empty.
3378 if (mQueuedErrors.size() == 1) {
3379 showError(errDialog);
3380 }
3381 }
3382
3383 private void showError(ErrorDialog errDialog) {
3384 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3385 .setTitle(errDialog.mTitle)
3386 .setMessage(errDialog.mDescription)
3387 .setPositiveButton(R.string.ok, null)
3388 .create();
3389 d.setOnDismissListener(mDialogListener);
3390 d.show();
3391 }
3392
The Android Open Source Project0c908882009-03-03 19:32:16 -08003393 /**
3394 * Show a dialog informing the user of the network error reported by
3395 * WebCore.
3396 */
3397 @Override
3398 public void onReceivedError(WebView view, int errorCode,
3399 String description, String failingUrl) {
3400 if (errorCode != EventHandler.ERROR_LOOKUP &&
3401 errorCode != EventHandler.ERROR_CONNECT &&
3402 errorCode != EventHandler.ERROR_BAD_URL &&
3403 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3404 errorCode != EventHandler.FILE_ERROR) {
Patrick Scott37911c72009-03-24 18:02:58 -07003405 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003406 }
Patrick Scott37911c72009-03-24 18:02:58 -07003407 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3408 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003409
3410 // We need to reset the title after an error.
3411 resetTitleAndRevertLockIcon();
3412 }
3413
3414 /**
3415 * Check with the user if it is ok to resend POST data as the page they
3416 * are trying to navigate to is the result of a POST.
3417 */
3418 @Override
3419 public void onFormResubmission(WebView view, final Message dontResend,
3420 final Message resend) {
3421 new AlertDialog.Builder(BrowserActivity.this)
3422 .setTitle(R.string.browserFrameFormResubmitLabel)
3423 .setMessage(R.string.browserFrameFormResubmitMessage)
3424 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3425 public void onClick(DialogInterface dialog, int which) {
3426 resend.sendToTarget();
3427 }})
3428 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3429 public void onClick(DialogInterface dialog, int which) {
3430 dontResend.sendToTarget();
3431 }})
3432 .setOnCancelListener(new OnCancelListener() {
3433 public void onCancel(DialogInterface dialog) {
3434 dontResend.sendToTarget();
3435 }})
3436 .show();
3437 }
3438
3439 /**
3440 * Insert the url into the visited history database.
3441 * @param url The url to be inserted.
3442 * @param isReload True if this url is being reloaded.
3443 * FIXME: Not sure what to do when reloading the page.
3444 */
3445 @Override
3446 public void doUpdateVisitedHistory(WebView view, String url,
3447 boolean isReload) {
3448 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3449 return;
3450 }
3451 Browser.updateVisitedHistory(mResolver, url, true);
3452 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3453 }
3454
3455 /**
3456 * Displays SSL error(s) dialog to the user.
3457 */
3458 @Override
3459 public void onReceivedSslError(
3460 final WebView view, final SslErrorHandler handler, final SslError error) {
3461
3462 if (mSettings.showSecurityWarnings()) {
3463 final LayoutInflater factory =
3464 LayoutInflater.from(BrowserActivity.this);
3465 final View warningsView =
3466 factory.inflate(R.layout.ssl_warnings, null);
3467 final LinearLayout placeholder =
3468 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3469
3470 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3471 LinearLayout ll = (LinearLayout)factory
3472 .inflate(R.layout.ssl_warning, null);
3473 ((TextView)ll.findViewById(R.id.warning))
3474 .setText(R.string.ssl_untrusted);
3475 placeholder.addView(ll);
3476 }
3477
3478 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3479 LinearLayout ll = (LinearLayout)factory
3480 .inflate(R.layout.ssl_warning, null);
3481 ((TextView)ll.findViewById(R.id.warning))
3482 .setText(R.string.ssl_mismatch);
3483 placeholder.addView(ll);
3484 }
3485
3486 if (error.hasError(SslError.SSL_EXPIRED)) {
3487 LinearLayout ll = (LinearLayout)factory
3488 .inflate(R.layout.ssl_warning, null);
3489 ((TextView)ll.findViewById(R.id.warning))
3490 .setText(R.string.ssl_expired);
3491 placeholder.addView(ll);
3492 }
3493
3494 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3495 LinearLayout ll = (LinearLayout)factory
3496 .inflate(R.layout.ssl_warning, null);
3497 ((TextView)ll.findViewById(R.id.warning))
3498 .setText(R.string.ssl_not_yet_valid);
3499 placeholder.addView(ll);
3500 }
3501
3502 new AlertDialog.Builder(BrowserActivity.this)
3503 .setTitle(R.string.security_warning)
3504 .setIcon(android.R.drawable.ic_dialog_alert)
3505 .setView(warningsView)
3506 .setPositiveButton(R.string.ssl_continue,
3507 new DialogInterface.OnClickListener() {
3508 public void onClick(DialogInterface dialog, int whichButton) {
3509 handler.proceed();
3510 }
3511 })
3512 .setNeutralButton(R.string.view_certificate,
3513 new DialogInterface.OnClickListener() {
3514 public void onClick(DialogInterface dialog, int whichButton) {
3515 showSSLCertificateOnError(view, handler, error);
3516 }
3517 })
3518 .setNegativeButton(R.string.cancel,
3519 new DialogInterface.OnClickListener() {
3520 public void onClick(DialogInterface dialog, int whichButton) {
3521 handler.cancel();
3522 BrowserActivity.this.resetTitleAndRevertLockIcon();
3523 }
3524 })
3525 .setOnCancelListener(
3526 new DialogInterface.OnCancelListener() {
3527 public void onCancel(DialogInterface dialog) {
3528 handler.cancel();
3529 BrowserActivity.this.resetTitleAndRevertLockIcon();
3530 }
3531 })
3532 .show();
3533 } else {
3534 handler.proceed();
3535 }
3536 }
3537
3538 /**
3539 * Handles an HTTP authentication request.
3540 *
3541 * @param handler The authentication handler
3542 * @param host The host
3543 * @param realm The realm
3544 */
3545 @Override
3546 public void onReceivedHttpAuthRequest(WebView view,
3547 final HttpAuthHandler handler, final String host, final String realm) {
3548 String username = null;
3549 String password = null;
3550
3551 boolean reuseHttpAuthUsernamePassword =
3552 handler.useHttpAuthUsernamePassword();
3553
3554 if (reuseHttpAuthUsernamePassword &&
3555 (mTabControl.getCurrentWebView() != null)) {
3556 String[] credentials =
3557 mTabControl.getCurrentWebView()
3558 .getHttpAuthUsernamePassword(host, realm);
3559 if (credentials != null && credentials.length == 2) {
3560 username = credentials[0];
3561 password = credentials[1];
3562 }
3563 }
3564
3565 if (username != null && password != null) {
3566 handler.proceed(username, password);
3567 } else {
3568 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3569 }
3570 }
3571
3572 @Override
3573 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3574 if (mMenuIsDown) {
3575 // only check shortcut key when MENU is held
3576 return getWindow().isShortcutKey(event.getKeyCode(), event);
3577 } else {
3578 return false;
3579 }
3580 }
3581
3582 @Override
3583 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3584 if (view != mTabControl.getCurrentTopWebView()) {
3585 return;
3586 }
3587 if (event.isDown()) {
3588 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3589 } else {
3590 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3591 }
3592 }
3593 };
3594
3595 //--------------------------------------------------------------------------
3596 // WebChromeClient implementation
3597 //--------------------------------------------------------------------------
3598
3599 /* package */ WebChromeClient getWebChromeClient() {
3600 return mWebChromeClient;
3601 }
3602
3603 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3604 // Helper method to create a new tab or sub window.
3605 private void createWindow(final boolean dialog, final Message msg) {
3606 if (dialog) {
3607 mTabControl.createSubWindow();
3608 final TabControl.Tab t = mTabControl.getCurrentTab();
3609 attachSubWindow(t);
3610 WebView.WebViewTransport transport =
3611 (WebView.WebViewTransport) msg.obj;
3612 transport.setWebView(t.getSubWebView());
3613 msg.sendToTarget();
3614 } else {
3615 final TabControl.Tab parent = mTabControl.getCurrentTab();
3616 // openTabAndShow will dispatch the message after creating the
3617 // new WebView. This will prevent another request from coming
3618 // in during the animation.
Patrick Scott1536e732009-06-11 14:50:01 -04003619 final TabControl.Tab newTab =
3620 openTabAndShow(EMPTY_URL_DATA, msg, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003621 if (newTab != parent) {
3622 parent.addChildTab(newTab);
3623 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003624 WebView.WebViewTransport transport =
3625 (WebView.WebViewTransport) msg.obj;
3626 transport.setWebView(mTabControl.getCurrentWebView());
3627 }
3628 }
3629
3630 @Override
3631 public boolean onCreateWindow(WebView view, final boolean dialog,
3632 final boolean userGesture, final Message resultMsg) {
3633 // Ignore these requests during tab animations or if the tab
3634 // overview is showing.
3635 if (mAnimationCount > 0 || mTabOverview != null) {
3636 return false;
3637 }
3638 // Short-circuit if we can't create any more tabs or sub windows.
3639 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3640 new AlertDialog.Builder(BrowserActivity.this)
3641 .setTitle(R.string.too_many_subwindows_dialog_title)
3642 .setIcon(android.R.drawable.ic_dialog_alert)
3643 .setMessage(R.string.too_many_subwindows_dialog_message)
3644 .setPositiveButton(R.string.ok, null)
3645 .show();
3646 return false;
3647 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3648 new AlertDialog.Builder(BrowserActivity.this)
3649 .setTitle(R.string.too_many_windows_dialog_title)
3650 .setIcon(android.R.drawable.ic_dialog_alert)
3651 .setMessage(R.string.too_many_windows_dialog_message)
3652 .setPositiveButton(R.string.ok, null)
3653 .show();
3654 return false;
3655 }
3656
3657 // Short-circuit if this was a user gesture.
3658 if (userGesture) {
3659 // createWindow will call openTabAndShow for new Windows and
3660 // that will call tabPicker which will increment
3661 // mAnimationCount.
3662 createWindow(dialog, resultMsg);
3663 return true;
3664 }
3665
3666 // Allow the popup and create the appropriate window.
3667 final AlertDialog.OnClickListener allowListener =
3668 new AlertDialog.OnClickListener() {
3669 public void onClick(DialogInterface d,
3670 int which) {
3671 // Same comment as above for setting
3672 // mAnimationCount.
3673 createWindow(dialog, resultMsg);
3674 // Since we incremented mAnimationCount while the
3675 // dialog was up, we have to decrement it here.
3676 mAnimationCount--;
3677 }
3678 };
3679
3680 // Block the popup by returning a null WebView.
3681 final AlertDialog.OnClickListener blockListener =
3682 new AlertDialog.OnClickListener() {
3683 public void onClick(DialogInterface d, int which) {
3684 resultMsg.sendToTarget();
3685 // We are not going to trigger an animation so
3686 // unblock keys and animation requests.
3687 mAnimationCount--;
3688 }
3689 };
3690
3691 // Build a confirmation dialog to display to the user.
3692 final AlertDialog d =
3693 new AlertDialog.Builder(BrowserActivity.this)
3694 .setTitle(R.string.attention)
3695 .setIcon(android.R.drawable.ic_dialog_alert)
3696 .setMessage(R.string.popup_window_attempt)
3697 .setPositiveButton(R.string.allow, allowListener)
3698 .setNegativeButton(R.string.block, blockListener)
3699 .setCancelable(false)
3700 .create();
3701
3702 // Show the confirmation dialog.
3703 d.show();
3704 // We want to increment mAnimationCount here to prevent a
3705 // potential race condition. If the user allows a pop-up from a
3706 // site and that pop-up then triggers another pop-up, it is
3707 // possible to get the BACK key between here and when the dialog
3708 // appears.
3709 mAnimationCount++;
3710 return true;
3711 }
3712
3713 @Override
3714 public void onCloseWindow(WebView window) {
3715 final int currentIndex = mTabControl.getCurrentIndex();
3716 final TabControl.Tab parent =
3717 mTabControl.getCurrentTab().getParentTab();
3718 if (parent != null) {
3719 // JavaScript can only close popup window.
3720 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3721 }
3722 }
3723
3724 @Override
3725 public void onProgressChanged(WebView view, int newProgress) {
3726 // Block progress updates to the title bar while the tab overview
3727 // is animating or being displayed.
3728 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04003729 if (CUSTOM_BROWSER_BAR) {
3730 mTitleBar.setProgress(newProgress);
3731 } else {
3732 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3733 newProgress * 100);
3734
3735 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003736 }
3737
3738 if (newProgress == 100) {
3739 // onProgressChanged() is called for sub-frame too while
3740 // onPageFinished() is only called for the main frame. sync
3741 // cookie and cache promptly here.
3742 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003743 if (mInLoad) {
3744 mInLoad = false;
3745 updateInLoadMenuItems();
3746 }
3747 } else {
3748 // onPageFinished may have already been called but a subframe
3749 // is still loading and updating the progress. Reset mInLoad
3750 // and update the menu items.
3751 if (!mInLoad) {
3752 mInLoad = true;
3753 updateInLoadMenuItems();
3754 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003755 }
3756 }
3757
3758 @Override
3759 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003760 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003761
3762 // here, if url is null, we want to reset the title
3763 setUrlTitle(url, title);
3764
3765 if (url == null ||
3766 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3767 return;
3768 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003769 // See if we can find the current url in our history database and
3770 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003771 if (url.startsWith("http://www.")) {
3772 url = url.substring(11);
3773 } else if (url.startsWith("http://")) {
3774 url = url.substring(4);
3775 }
3776 try {
3777 url = "%" + url;
3778 String [] selArgs = new String[] { url };
3779
3780 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3781 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3782 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3783 Browser.HISTORY_PROJECTION, where, selArgs, null);
3784 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003785 // Current implementation of database only has one entry per
3786 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003787 ContentValues map = new ContentValues();
3788 map.put(Browser.BookmarkColumns.TITLE, title);
3789 mResolver.update(Browser.BOOKMARKS_URI, map,
3790 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003791 }
3792 c.close();
3793 } catch (IllegalStateException e) {
3794 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3795 } catch (SQLiteException ex) {
3796 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3797 }
3798 }
3799
3800 @Override
3801 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003802 updateIcon(view, icon);
3803 }
3804
3805 @Override
3806 public void onReceivedTouchIconUrl(WebView view, String url) {
3807 final ContentResolver cr = getContentResolver();
3808 final Cursor c =
3809 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003810 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003811 if (c != null) {
3812 if (c.getCount() > 0) {
3813 new DownloadTouchIcon(cr, c, view).execute(url);
3814 } else {
3815 c.close();
3816 }
3817 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003818 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003819
Andrei Popescuadc008d2009-06-26 14:11:30 +01003820 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003821 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003822 if (mCustomView != null)
3823 return;
3824
3825 // Add the custom view to its container.
3826 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3827 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003828 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003829 // Save the menu state and set it to empty while the custom
3830 // view is showing.
3831 mOldMenuState = mMenuState;
3832 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003833 // Hide the content view.
3834 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003835 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003836 mCustomViewContainer.setVisibility(View.VISIBLE);
3837 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003838 }
3839
3840 @Override
3841 public void onHideCustomView() {
3842 if (mCustomView == null)
3843 return;
3844
Andrei Popescuc9b55562009-07-07 10:51:15 +01003845 // Hide the custom view.
3846 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003847 // Remove the custom view from its container.
3848 mCustomViewContainer.removeView(mCustomView);
3849 mCustomView = null;
3850 // Reset the old menu state.
3851 mMenuState = mOldMenuState;
3852 mOldMenuState = EMPTY_MENU;
3853 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003854 mCustomViewCallback.onCustomViewHidden();
3855 // Show the content view.
3856 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003857 }
3858
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003859 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003860 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003861 * @param url the URL that exceeded the quota
3862 * @param databaseIdentifier the identifier of the database on
3863 * which the transaction that caused the quota overflow was run
3864 * @param currentQuota the current quota for the origin.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003865 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003866 * @param quotaUpdater The callback to run when a decision to allow or
3867 * deny quota has been made. Don't forget to call this!
3868 */
3869 @Override
3870 public void onExceededDatabaseQuota(String url,
Andrei Popescu79e82b72009-07-27 12:01:59 +01003871 String databaseIdentifier, long currentQuota, long totalUsedQuota,
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003872 WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003873 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
3874 url, databaseIdentifier, currentQuota, totalUsedQuota,
3875 quotaUpdater);
3876 }
3877
3878 /**
3879 * The Application Cache has exceeded its max size.
3880 * @param spaceNeeded is the amount of disk space that would be needed
3881 * in order for the last appcache operation to succeed.
3882 * @param totalUsedQuota is the sum of all origins' quota.
3883 * @param quotaUpdater A callback to inform the WebCore thread that a new
3884 * app cache size is available. This callback must always be executed at
3885 * some point to ensure that the sleeping WebCore thread is woken up.
3886 */
3887 @Override
3888 public void onReachedMaxAppCacheSize(long spaceNeeded,
3889 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3890 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3891 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003892 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003893
Steve Block2bc69912009-07-30 14:45:13 +01003894 /**
3895 * Instructs the browser to show a prompt to ask the user to set the
3896 * Geolocation permission state for the specified origin.
3897 * @param origin The origin for which Geolocation permissions are
3898 * requested.
3899 * @param callback The callback to call once the user has set the
3900 * Geolocation permission state.
3901 */
3902 @Override
3903 public void onGeolocationPermissionsShowPrompt(String origin,
3904 GeolocationPermissions.Callback callback) {
3905 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3906 origin, callback);
3907 }
3908
3909 /**
3910 * Instructs the browser to hide the Geolocation permissions prompt.
3911 */
3912 @Override
3913 public void onGeolocationPermissionsHidePrompt() {
3914 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3915 }
3916
Ben Murdoch7db26342009-06-03 18:21:19 +01003917 /* Adds a JavaScript error message to the system log.
3918 * @param message The error message to report.
3919 * @param lineNumber The line number of the error.
3920 * @param sourceID The name of the source file that caused the error.
3921 */
3922 @Override
3923 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003924 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3925 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3926 if (mShouldShowErrorConsole &&
3927 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3928 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3929 }
3930 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003931 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003932 };
3933
3934 /**
3935 * Notify the host application a download should be done, or that
3936 * the data should be streamed if a streaming viewer is available.
3937 * @param url The full url to the content that should be downloaded
3938 * @param contentDisposition Content-disposition http header, if
3939 * present.
3940 * @param mimetype The mimetype of the content reported by the server
3941 * @param contentLength The file size reported by the server
3942 */
3943 public void onDownloadStart(String url, String userAgent,
3944 String contentDisposition, String mimetype, long contentLength) {
3945 // if we're dealing wih A/V content that's not explicitly marked
3946 // for download, check if it's streamable.
3947 if (contentDisposition == null
3948 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3949 // query the package manager to see if there's a registered handler
3950 // that matches.
3951 Intent intent = new Intent(Intent.ACTION_VIEW);
3952 intent.setDataAndType(Uri.parse(url), mimetype);
3953 if (getPackageManager().resolveActivity(intent,
3954 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3955 // someone knows how to handle this mime type with this scheme, don't download.
3956 try {
3957 startActivity(intent);
3958 return;
3959 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003960 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003961 Log.d(LOGTAG, "activity not found for " + mimetype
3962 + " over " + Uri.parse(url).getScheme(), ex);
3963 }
3964 // Best behavior is to fall back to a download in this case
3965 }
3966 }
3967 }
3968 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3969 }
3970
3971 /**
3972 * Notify the host application a download should be done, even if there
3973 * is a streaming viewer available for thise type.
3974 * @param url The full url to the content that should be downloaded
3975 * @param contentDisposition Content-disposition http header, if
3976 * present.
3977 * @param mimetype The mimetype of the content reported by the server
3978 * @param contentLength The file size reported by the server
3979 */
3980 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3981 String contentDisposition, String mimetype, long contentLength) {
3982
3983 String filename = URLUtil.guessFileName(url,
3984 contentDisposition, mimetype);
3985
3986 // Check to see if we have an SDCard
3987 String status = Environment.getExternalStorageState();
3988 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3989 int title;
3990 String msg;
3991
3992 // Check to see if the SDCard is busy, same as the music app
3993 if (status.equals(Environment.MEDIA_SHARED)) {
3994 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3995 title = R.string.download_sdcard_busy_dlg_title;
3996 } else {
3997 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3998 title = R.string.download_no_sdcard_dlg_title;
3999 }
4000
4001 new AlertDialog.Builder(this)
4002 .setTitle(title)
4003 .setIcon(android.R.drawable.ic_dialog_alert)
4004 .setMessage(msg)
4005 .setPositiveButton(R.string.ok, null)
4006 .show();
4007 return;
4008 }
4009
4010 // java.net.URI is a lot stricter than KURL so we have to undo
4011 // KURL's percent-encoding and redo the encoding using java.net.URI.
4012 URI uri = null;
4013 try {
4014 // Undo the percent-encoding that KURL may have done.
4015 String newUrl = new String(URLUtil.decode(url.getBytes()));
4016 // Parse the url into pieces
4017 WebAddress w = new WebAddress(newUrl);
4018 String frag = null;
4019 String query = null;
4020 String path = w.mPath;
4021 // Break the path into path, query, and fragment
4022 if (path.length() > 0) {
4023 // Strip the fragment
4024 int idx = path.lastIndexOf('#');
4025 if (idx != -1) {
4026 frag = path.substring(idx + 1);
4027 path = path.substring(0, idx);
4028 }
4029 idx = path.lastIndexOf('?');
4030 if (idx != -1) {
4031 query = path.substring(idx + 1);
4032 path = path.substring(0, idx);
4033 }
4034 }
4035 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
4036 query, frag);
4037 } catch (Exception e) {
4038 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
4039 return;
4040 }
4041
4042 // XXX: Have to use the old url since the cookies were stored using the
4043 // old percent-encoded url.
4044 String cookies = CookieManager.getInstance().getCookie(url);
4045
4046 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07004047 values.put(Downloads.COLUMN_URI, uri.toString());
4048 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
4049 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
4050 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08004051 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07004052 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08004053 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07004054 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
4055 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
4056 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
4057 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004058 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07004059 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004060 }
4061 if (mimetype == null) {
4062 // We must have long pressed on a link or image to download it. We
4063 // are not sure of the mimetype in this case, so do a head request
4064 new FetchUrlMimeType(this).execute(values);
4065 } else {
4066 final Uri contentUri =
4067 getContentResolver().insert(Downloads.CONTENT_URI, values);
4068 viewDownloads(contentUri);
4069 }
4070
4071 }
4072
4073 /**
4074 * Resets the lock icon. This method is called when we start a new load and
4075 * know the url to be loaded.
4076 */
4077 private void resetLockIcon(String url) {
4078 // Save the lock-icon state (we revert to it if the load gets cancelled)
4079 saveLockIcon();
4080
4081 mLockIconType = LOCK_ICON_UNSECURE;
4082 if (URLUtil.isHttpsUrl(url)) {
4083 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07004084 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004085 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
4086 " reset lock icon to " + mLockIconType);
4087 }
4088 }
4089
4090 updateLockIconImage(LOCK_ICON_UNSECURE);
4091 }
4092
4093 /**
4094 * Resets the lock icon. This method is called when the icon needs to be
4095 * reset but we do not know whether we are loading a secure or not secure
4096 * page.
4097 */
4098 private void resetLockIcon() {
4099 // Save the lock-icon state (we revert to it if the load gets cancelled)
4100 saveLockIcon();
4101
4102 mLockIconType = LOCK_ICON_UNSECURE;
4103
Dave Bort31a6d1c2009-04-13 15:56:49 -07004104 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004105 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
4106 " reset lock icon to " + mLockIconType);
4107 }
4108
4109 updateLockIconImage(LOCK_ICON_UNSECURE);
4110 }
4111
4112 /**
4113 * Updates the lock-icon image in the title-bar.
4114 */
4115 private void updateLockIconImage(int lockIconType) {
4116 Drawable d = null;
4117 if (lockIconType == LOCK_ICON_SECURE) {
4118 d = mSecLockIcon;
4119 } else if (lockIconType == LOCK_ICON_MIXED) {
4120 d = mMixLockIcon;
4121 }
4122 // If the tab overview is animating or being shown, do not update the
4123 // lock icon.
4124 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04004125 if (CUSTOM_BROWSER_BAR) {
4126 mTitleBar.setLock(d);
4127 } else {
4128 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
4129 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004130 }
4131 }
4132
4133 /**
4134 * Displays a page-info dialog.
4135 * @param tab The tab to show info about
4136 * @param fromShowSSLCertificateOnError The flag that indicates whether
4137 * this dialog was opened from the SSL-certificate-on-error dialog or
4138 * not. This is important, since we need to know whether to return to
4139 * the parent dialog or simply dismiss.
4140 */
4141 private void showPageInfo(final TabControl.Tab tab,
4142 final boolean fromShowSSLCertificateOnError) {
4143 final LayoutInflater factory = LayoutInflater
4144 .from(this);
4145
4146 final View pageInfoView = factory.inflate(R.layout.page_info, null);
4147
4148 final WebView view = tab.getWebView();
4149
4150 String url = null;
4151 String title = null;
4152
4153 if (view == null) {
4154 url = tab.getUrl();
4155 title = tab.getTitle();
4156 } else if (view == mTabControl.getCurrentWebView()) {
4157 // Use the cached title and url if this is the current WebView
4158 url = mUrl;
4159 title = mTitle;
4160 } else {
4161 url = view.getUrl();
4162 title = view.getTitle();
4163 }
4164
4165 if (url == null) {
4166 url = "";
4167 }
4168 if (title == null) {
4169 title = "";
4170 }
4171
4172 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
4173 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
4174
4175 mPageInfoView = tab;
4176 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
4177
4178 AlertDialog.Builder alertDialogBuilder =
4179 new AlertDialog.Builder(this)
4180 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
4181 .setView(pageInfoView)
4182 .setPositiveButton(
4183 R.string.ok,
4184 new DialogInterface.OnClickListener() {
4185 public void onClick(DialogInterface dialog,
4186 int whichButton) {
4187 mPageInfoDialog = null;
4188 mPageInfoView = null;
4189 mPageInfoFromShowSSLCertificateOnError = null;
4190
4191 // if we came here from the SSL error dialog
4192 if (fromShowSSLCertificateOnError) {
4193 // go back to the SSL error dialog
4194 showSSLCertificateOnError(
4195 mSSLCertificateOnErrorView,
4196 mSSLCertificateOnErrorHandler,
4197 mSSLCertificateOnErrorError);
4198 }
4199 }
4200 })
4201 .setOnCancelListener(
4202 new DialogInterface.OnCancelListener() {
4203 public void onCancel(DialogInterface dialog) {
4204 mPageInfoDialog = null;
4205 mPageInfoView = null;
4206 mPageInfoFromShowSSLCertificateOnError = null;
4207
4208 // if we came here from the SSL error dialog
4209 if (fromShowSSLCertificateOnError) {
4210 // go back to the SSL error dialog
4211 showSSLCertificateOnError(
4212 mSSLCertificateOnErrorView,
4213 mSSLCertificateOnErrorHandler,
4214 mSSLCertificateOnErrorError);
4215 }
4216 }
4217 });
4218
4219 // if we have a main top-level page SSL certificate set or a certificate
4220 // error
4221 if (fromShowSSLCertificateOnError ||
4222 (view != null && view.getCertificate() != null)) {
4223 // add a 'View Certificate' button
4224 alertDialogBuilder.setNeutralButton(
4225 R.string.view_certificate,
4226 new DialogInterface.OnClickListener() {
4227 public void onClick(DialogInterface dialog,
4228 int whichButton) {
4229 mPageInfoDialog = null;
4230 mPageInfoView = null;
4231 mPageInfoFromShowSSLCertificateOnError = null;
4232
4233 // if we came here from the SSL error dialog
4234 if (fromShowSSLCertificateOnError) {
4235 // go back to the SSL error dialog
4236 showSSLCertificateOnError(
4237 mSSLCertificateOnErrorView,
4238 mSSLCertificateOnErrorHandler,
4239 mSSLCertificateOnErrorError);
4240 } else {
4241 // otherwise, display the top-most certificate from
4242 // the chain
4243 if (view.getCertificate() != null) {
4244 showSSLCertificate(tab);
4245 }
4246 }
4247 }
4248 });
4249 }
4250
4251 mPageInfoDialog = alertDialogBuilder.show();
4252 }
4253
4254 /**
4255 * Displays the main top-level page SSL certificate dialog
4256 * (accessible from the Page-Info dialog).
4257 * @param tab The tab to show certificate for.
4258 */
4259 private void showSSLCertificate(final TabControl.Tab tab) {
4260 final View certificateView =
4261 inflateCertificateView(tab.getWebView().getCertificate());
4262 if (certificateView == null) {
4263 return;
4264 }
4265
4266 LayoutInflater factory = LayoutInflater.from(this);
4267
4268 final LinearLayout placeholder =
4269 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4270
4271 LinearLayout ll = (LinearLayout) factory.inflate(
4272 R.layout.ssl_success, placeholder);
4273 ((TextView)ll.findViewById(R.id.success))
4274 .setText(R.string.ssl_certificate_is_valid);
4275
4276 mSSLCertificateView = tab;
4277 mSSLCertificateDialog =
4278 new AlertDialog.Builder(this)
4279 .setTitle(R.string.ssl_certificate).setIcon(
4280 R.drawable.ic_dialog_browser_certificate_secure)
4281 .setView(certificateView)
4282 .setPositiveButton(R.string.ok,
4283 new DialogInterface.OnClickListener() {
4284 public void onClick(DialogInterface dialog,
4285 int whichButton) {
4286 mSSLCertificateDialog = null;
4287 mSSLCertificateView = null;
4288
4289 showPageInfo(tab, false);
4290 }
4291 })
4292 .setOnCancelListener(
4293 new DialogInterface.OnCancelListener() {
4294 public void onCancel(DialogInterface dialog) {
4295 mSSLCertificateDialog = null;
4296 mSSLCertificateView = null;
4297
4298 showPageInfo(tab, false);
4299 }
4300 })
4301 .show();
4302 }
4303
4304 /**
4305 * Displays the SSL error certificate dialog.
4306 * @param view The target web-view.
4307 * @param handler The SSL error handler responsible for cancelling the
4308 * connection that resulted in an SSL error or proceeding per user request.
4309 * @param error The SSL error object.
4310 */
4311 private void showSSLCertificateOnError(
4312 final WebView view, final SslErrorHandler handler, final SslError error) {
4313
4314 final View certificateView =
4315 inflateCertificateView(error.getCertificate());
4316 if (certificateView == null) {
4317 return;
4318 }
4319
4320 LayoutInflater factory = LayoutInflater.from(this);
4321
4322 final LinearLayout placeholder =
4323 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4324
4325 if (error.hasError(SslError.SSL_UNTRUSTED)) {
4326 LinearLayout ll = (LinearLayout)factory
4327 .inflate(R.layout.ssl_warning, placeholder);
4328 ((TextView)ll.findViewById(R.id.warning))
4329 .setText(R.string.ssl_untrusted);
4330 }
4331
4332 if (error.hasError(SslError.SSL_IDMISMATCH)) {
4333 LinearLayout ll = (LinearLayout)factory
4334 .inflate(R.layout.ssl_warning, placeholder);
4335 ((TextView)ll.findViewById(R.id.warning))
4336 .setText(R.string.ssl_mismatch);
4337 }
4338
4339 if (error.hasError(SslError.SSL_EXPIRED)) {
4340 LinearLayout ll = (LinearLayout)factory
4341 .inflate(R.layout.ssl_warning, placeholder);
4342 ((TextView)ll.findViewById(R.id.warning))
4343 .setText(R.string.ssl_expired);
4344 }
4345
4346 if (error.hasError(SslError.SSL_NOTYETVALID)) {
4347 LinearLayout ll = (LinearLayout)factory
4348 .inflate(R.layout.ssl_warning, placeholder);
4349 ((TextView)ll.findViewById(R.id.warning))
4350 .setText(R.string.ssl_not_yet_valid);
4351 }
4352
4353 mSSLCertificateOnErrorHandler = handler;
4354 mSSLCertificateOnErrorView = view;
4355 mSSLCertificateOnErrorError = error;
4356 mSSLCertificateOnErrorDialog =
4357 new AlertDialog.Builder(this)
4358 .setTitle(R.string.ssl_certificate).setIcon(
4359 R.drawable.ic_dialog_browser_certificate_partially_secure)
4360 .setView(certificateView)
4361 .setPositiveButton(R.string.ok,
4362 new DialogInterface.OnClickListener() {
4363 public void onClick(DialogInterface dialog,
4364 int whichButton) {
4365 mSSLCertificateOnErrorDialog = null;
4366 mSSLCertificateOnErrorView = null;
4367 mSSLCertificateOnErrorHandler = null;
4368 mSSLCertificateOnErrorError = null;
4369
4370 mWebViewClient.onReceivedSslError(
4371 view, handler, error);
4372 }
4373 })
4374 .setNeutralButton(R.string.page_info_view,
4375 new DialogInterface.OnClickListener() {
4376 public void onClick(DialogInterface dialog,
4377 int whichButton) {
4378 mSSLCertificateOnErrorDialog = null;
4379
4380 // do not clear the dialog state: we will
4381 // need to show the dialog again once the
4382 // user is done exploring the page-info details
4383
4384 showPageInfo(mTabControl.getTabFromView(view),
4385 true);
4386 }
4387 })
4388 .setOnCancelListener(
4389 new DialogInterface.OnCancelListener() {
4390 public void onCancel(DialogInterface dialog) {
4391 mSSLCertificateOnErrorDialog = null;
4392 mSSLCertificateOnErrorView = null;
4393 mSSLCertificateOnErrorHandler = null;
4394 mSSLCertificateOnErrorError = null;
4395
4396 mWebViewClient.onReceivedSslError(
4397 view, handler, error);
4398 }
4399 })
4400 .show();
4401 }
4402
4403 /**
4404 * Inflates the SSL certificate view (helper method).
4405 * @param certificate The SSL certificate.
4406 * @return The resultant certificate view with issued-to, issued-by,
4407 * issued-on, expires-on, and possibly other fields set.
4408 * If the input certificate is null, returns null.
4409 */
4410 private View inflateCertificateView(SslCertificate certificate) {
4411 if (certificate == null) {
4412 return null;
4413 }
4414
4415 LayoutInflater factory = LayoutInflater.from(this);
4416
4417 View certificateView = factory.inflate(
4418 R.layout.ssl_certificate, null);
4419
4420 // issued to:
4421 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4422 if (issuedTo != null) {
4423 ((TextView) certificateView.findViewById(R.id.to_common))
4424 .setText(issuedTo.getCName());
4425 ((TextView) certificateView.findViewById(R.id.to_org))
4426 .setText(issuedTo.getOName());
4427 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4428 .setText(issuedTo.getUName());
4429 }
4430
4431 // issued by:
4432 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4433 if (issuedBy != null) {
4434 ((TextView) certificateView.findViewById(R.id.by_common))
4435 .setText(issuedBy.getCName());
4436 ((TextView) certificateView.findViewById(R.id.by_org))
4437 .setText(issuedBy.getOName());
4438 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4439 .setText(issuedBy.getUName());
4440 }
4441
4442 // issued on:
4443 String issuedOn = reformatCertificateDate(
4444 certificate.getValidNotBefore());
4445 ((TextView) certificateView.findViewById(R.id.issued_on))
4446 .setText(issuedOn);
4447
4448 // expires on:
4449 String expiresOn = reformatCertificateDate(
4450 certificate.getValidNotAfter());
4451 ((TextView) certificateView.findViewById(R.id.expires_on))
4452 .setText(expiresOn);
4453
4454 return certificateView;
4455 }
4456
4457 /**
4458 * Re-formats the certificate date (Date.toString()) string to
4459 * a properly localized date string.
4460 * @return Properly localized version of the certificate date string and
4461 * the original certificate date string if fails to localize.
4462 * If the original string is null, returns an empty string "".
4463 */
4464 private String reformatCertificateDate(String certificateDate) {
4465 String reformattedDate = null;
4466
4467 if (certificateDate != null) {
4468 Date date = null;
4469 try {
4470 date = java.text.DateFormat.getInstance().parse(certificateDate);
4471 } catch (ParseException e) {
4472 date = null;
4473 }
4474
4475 if (date != null) {
4476 reformattedDate =
4477 DateFormat.getDateFormat(this).format(date);
4478 }
4479 }
4480
4481 return reformattedDate != null ? reformattedDate :
4482 (certificateDate != null ? certificateDate : "");
4483 }
4484
4485 /**
4486 * Displays an http-authentication dialog.
4487 */
4488 private void showHttpAuthentication(final HttpAuthHandler handler,
4489 final String host, final String realm, final String title,
4490 final String name, final String password, int focusId) {
4491 LayoutInflater factory = LayoutInflater.from(this);
4492 final View v = factory
4493 .inflate(R.layout.http_authentication, null);
4494 if (name != null) {
4495 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4496 }
4497 if (password != null) {
4498 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4499 }
4500
4501 String titleText = title;
4502 if (titleText == null) {
4503 titleText = getText(R.string.sign_in_to).toString().replace(
4504 "%s1", host).replace("%s2", realm);
4505 }
4506
4507 mHttpAuthHandler = handler;
4508 AlertDialog dialog = new AlertDialog.Builder(this)
4509 .setTitle(titleText)
4510 .setIcon(android.R.drawable.ic_dialog_alert)
4511 .setView(v)
4512 .setPositiveButton(R.string.action,
4513 new DialogInterface.OnClickListener() {
4514 public void onClick(DialogInterface dialog,
4515 int whichButton) {
4516 String nm = ((EditText) v
4517 .findViewById(R.id.username_edit))
4518 .getText().toString();
4519 String pw = ((EditText) v
4520 .findViewById(R.id.password_edit))
4521 .getText().toString();
4522 BrowserActivity.this.setHttpAuthUsernamePassword
4523 (host, realm, nm, pw);
4524 handler.proceed(nm, pw);
4525 mHttpAuthenticationDialog = null;
4526 mHttpAuthHandler = null;
4527 }})
4528 .setNegativeButton(R.string.cancel,
4529 new DialogInterface.OnClickListener() {
4530 public void onClick(DialogInterface dialog,
4531 int whichButton) {
4532 handler.cancel();
4533 BrowserActivity.this.resetTitleAndRevertLockIcon();
4534 mHttpAuthenticationDialog = null;
4535 mHttpAuthHandler = null;
4536 }})
4537 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4538 public void onCancel(DialogInterface dialog) {
4539 handler.cancel();
4540 BrowserActivity.this.resetTitleAndRevertLockIcon();
4541 mHttpAuthenticationDialog = null;
4542 mHttpAuthHandler = null;
4543 }})
4544 .create();
4545 // Make the IME appear when the dialog is displayed if applicable.
4546 dialog.getWindow().setSoftInputMode(
4547 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4548 dialog.show();
4549 if (focusId != 0) {
4550 dialog.findViewById(focusId).requestFocus();
4551 } else {
4552 v.findViewById(R.id.username_edit).requestFocus();
4553 }
4554 mHttpAuthenticationDialog = dialog;
4555 }
4556
4557 public int getProgress() {
4558 WebView w = mTabControl.getCurrentWebView();
4559 if (w != null) {
4560 return w.getProgress();
4561 } else {
4562 return 100;
4563 }
4564 }
4565
4566 /**
4567 * Set HTTP authentication password.
4568 *
4569 * @param host The host for the password
4570 * @param realm The realm for the password
4571 * @param username The username for the password. If it is null, it means
4572 * password can't be saved.
4573 * @param password The password
4574 */
4575 public void setHttpAuthUsernamePassword(String host, String realm,
4576 String username,
4577 String password) {
4578 WebView w = mTabControl.getCurrentWebView();
4579 if (w != null) {
4580 w.setHttpAuthUsernamePassword(host, realm, username, password);
4581 }
4582 }
4583
4584 /**
4585 * connectivity manager says net has come or gone... inform the user
4586 * @param up true if net has come up, false if net has gone down
4587 */
4588 public void onNetworkToggle(boolean up) {
4589 if (up == mIsNetworkUp) {
4590 return;
4591 } else if (up) {
4592 mIsNetworkUp = true;
4593 if (mAlertDialog != null) {
4594 mAlertDialog.cancel();
4595 mAlertDialog = null;
4596 }
4597 } else {
4598 mIsNetworkUp = false;
4599 if (mInLoad && mAlertDialog == null) {
4600 mAlertDialog = new AlertDialog.Builder(this)
4601 .setTitle(R.string.loadSuspendedTitle)
4602 .setMessage(R.string.loadSuspended)
4603 .setPositiveButton(R.string.ok, null)
4604 .show();
4605 }
4606 }
4607 WebView w = mTabControl.getCurrentWebView();
4608 if (w != null) {
4609 w.setNetworkAvailable(up);
4610 }
4611 }
4612
4613 @Override
4614 protected void onActivityResult(int requestCode, int resultCode,
4615 Intent intent) {
4616 switch (requestCode) {
4617 case COMBO_PAGE:
4618 if (resultCode == RESULT_OK && intent != null) {
4619 String data = intent.getAction();
4620 Bundle extras = intent.getExtras();
4621 if (extras != null && extras.getBoolean("new_window", false)) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04004622 final TabControl.Tab newTab = openTab(data);
4623 if (mSettings.openInBackground() &&
4624 newTab != null && mTabOverview != null) {
4625 mTabControl.populatePickerData(newTab);
4626 mTabControl.setCurrentTab(newTab);
4627 mTabOverview.add(newTab);
4628 mTabOverview.setCurrentIndex(
4629 mTabControl.getCurrentIndex());
4630 sendAnimateFromOverview(newTab, false,
4631 EMPTY_URL_DATA, TAB_OVERVIEW_DELAY, null);
4632 }
Leon Scroggins64b80f32009-08-07 12:03:34 -04004633 } else if (intent.getBooleanExtra("open_search", false)) {
4634 onSearchRequested();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004635 } else {
4636 final TabControl.Tab currentTab =
4637 mTabControl.getCurrentTab();
4638 // If the Window overview is up and we are not in the
4639 // middle of an animation, animate away from it to the
4640 // current tab.
4641 if (mTabOverview != null && mAnimationCount == 0) {
Grace Klobaec7eb372009-06-16 13:45:56 -07004642 sendAnimateFromOverview(currentTab, false,
4643 new UrlData(data), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004644 } else {
4645 dismissSubWindow(currentTab);
4646 if (data != null && data.length() != 0) {
4647 getTopWindow().loadUrl(data);
4648 }
4649 }
4650 }
4651 }
4652 break;
4653 default:
4654 break;
4655 }
4656 getTopWindow().requestFocus();
4657 }
4658
4659 /*
4660 * This method is called as a result of the user selecting the options
4661 * menu to see the download window, or when a download changes state. It
4662 * shows the download window ontop of the current window.
4663 */
4664 /* package */ void viewDownloads(Uri downloadRecord) {
4665 Intent intent = new Intent(this,
4666 BrowserDownloadPage.class);
4667 intent.setData(downloadRecord);
4668 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4669
4670 }
4671
4672 /**
4673 * Handle results from Tab Switcher mTabOverview tool
4674 */
4675 private class TabListener implements ImageGrid.Listener {
4676 public void remove(int position) {
4677 // Note: Remove is not enabled if we have only one tab.
Dave Bort31a6d1c2009-04-13 15:56:49 -07004678 if (DEBUG && mTabControl.getTabCount() == 1) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004679 throw new AssertionError();
4680 }
4681
4682 // Remember the current tab.
4683 TabControl.Tab current = mTabControl.getCurrentTab();
4684 final TabControl.Tab remove = mTabControl.getTab(position);
4685 mTabControl.removeTab(remove);
4686 // If we removed the current tab, use the tab at position - 1 if
4687 // possible.
4688 if (current == remove) {
4689 // If the user removes the last tab, act like the New Tab item
4690 // was clicked on.
4691 if (mTabControl.getTabCount() == 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004692 current = mTabControl.createNewTab();
Leon Scroggins64b80f32009-08-07 12:03:34 -04004693 sendAnimateFromOverview(current, true, EMPTY_URL_DATA,
4694 TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004695 } else {
4696 final int index = position > 0 ? (position - 1) : 0;
4697 current = mTabControl.getTab(index);
4698 }
4699 }
4700
4701 // The tab overview could have been dismissed before this method is
4702 // called.
4703 if (mTabOverview != null) {
4704 // Remove the tab and change the index.
4705 mTabOverview.remove(position);
4706 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4707 }
4708
4709 // Only the current tab ensures its WebView is non-null. This
4710 // implies that we are reloading the freed tab.
4711 mTabControl.setCurrentTab(current);
4712 }
4713 public void onClick(int index) {
4714 // Change the tab if necessary.
4715 // Index equals ImageGrid.CANCEL when pressing back from the tab
4716 // overview.
4717 if (index == ImageGrid.CANCEL) {
4718 index = mTabControl.getCurrentIndex();
4719 // The current index is -1 if the current tab was removed.
4720 if (index == -1) {
4721 // Take the last tab as a fallback.
4722 index = mTabControl.getTabCount() - 1;
4723 }
4724 }
4725
The Android Open Source Project0c908882009-03-03 19:32:16 -08004726 // NEW_TAB means that the "New Tab" cell was clicked on.
4727 if (index == ImageGrid.NEW_TAB) {
Leon Scroggins64b80f32009-08-07 12:03:34 -04004728 openTabAndShow(EMPTY_URL_DATA, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004729 } else {
Grace Klobaec7eb372009-06-16 13:45:56 -07004730 sendAnimateFromOverview(mTabControl.getTab(index), false,
4731 EMPTY_URL_DATA, 0, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004732 }
4733 }
4734 }
4735
4736 // A fake View that draws the WebView's picture with a fast zoom filter.
4737 // The View is used in case the tab is freed during the animation because
4738 // of low memory.
4739 private static class AnimatingView extends View {
4740 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4741 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4742 private static final DrawFilter sZoomFilter =
4743 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4744 private final Picture mPicture;
4745 private final float mScale;
4746 private final int mScrollX;
4747 private final int mScrollY;
4748 final TabControl.Tab mTab;
4749
4750 AnimatingView(Context ctxt, TabControl.Tab t) {
4751 super(ctxt);
4752 mTab = t;
Patrick Scottae641ac2009-04-20 13:51:49 -04004753 if (t != null && t.getTopWindow() != null) {
4754 // Use the top window in the animation since the tab overview
4755 // will display the top window in each cell.
4756 final WebView w = t.getTopWindow();
4757 mPicture = w.capturePicture();
4758 mScale = w.getScale() / w.getWidth();
4759 mScrollX = w.getScrollX();
4760 mScrollY = w.getScrollY();
4761 } else {
4762 mPicture = null;
4763 mScale = 1.0f;
4764 mScrollX = mScrollY = 0;
4765 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004766 }
4767
4768 @Override
4769 protected void onDraw(Canvas canvas) {
4770 canvas.save();
4771 canvas.drawColor(Color.WHITE);
4772 if (mPicture != null) {
4773 canvas.setDrawFilter(sZoomFilter);
4774 float scale = getWidth() * mScale;
4775 canvas.scale(scale, scale);
4776 canvas.translate(-mScrollX, -mScrollY);
4777 canvas.drawPicture(mPicture);
4778 }
4779 canvas.restore();
4780 }
4781 }
4782
4783 /**
4784 * Open the tab picker. This function will always use the current tab in
4785 * its animation.
4786 * @param stay boolean stating whether the tab picker is to remain open
4787 * (in which case it needs a listener and its menu) or not.
4788 * @param index The index of the tab to show as the selection in the tab
4789 * overview.
4790 * @param remove If true, the tab at index will be removed after the
4791 * animation completes.
4792 */
4793 private void tabPicker(final boolean stay, final int index,
4794 final boolean remove) {
4795 if (mTabOverview != null) {
4796 return;
4797 }
4798
4799 int size = mTabControl.getTabCount();
4800
4801 TabListener l = null;
4802 if (stay) {
4803 l = mTabListener = new TabListener();
4804 }
4805 mTabOverview = new ImageGrid(this, stay, l);
4806
4807 for (int i = 0; i < size; i++) {
4808 final TabControl.Tab t = mTabControl.getTab(i);
4809 mTabControl.populatePickerData(t);
4810 mTabOverview.add(t);
4811 }
4812
4813 // Tell the tab overview to show the current tab, the tab overview will
4814 // handle the "New Tab" case.
4815 int currentIndex = mTabControl.getCurrentIndex();
4816 mTabOverview.setCurrentIndex(currentIndex);
4817
4818 // Attach the tab overview.
4819 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4820
4821 // Create a fake AnimatingView to animate the WebView's picture.
4822 final TabControl.Tab current = mTabControl.getCurrentTab();
4823 final AnimatingView v = new AnimatingView(this, current);
4824 mContentView.addView(v, COVER_SCREEN_PARAMS);
4825 removeTabFromContentView(current);
4826 // Pause timers to get the animation smoother.
4827 current.getWebView().pauseTimers();
4828
4829 // Send a message so the tab picker has a chance to layout and get
4830 // positions for all the cells.
4831 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4832 index, remove ? 1 : 0, v));
4833 // Setting this will indicate that we are animating to the overview. We
4834 // set it here to prevent another request to animate from coming in
4835 // between now and when ANIMATE_TO_OVERVIEW is handled.
4836 mAnimationCount++;
4837 // Always change the title bar to the window overview title while
4838 // animating.
Leon Scroggins81db3662009-06-04 17:45:11 -04004839 if (CUSTOM_BROWSER_BAR) {
4840 mTitleBar.setToTabPicker();
4841 } else {
4842 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4843 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4844 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4845 Window.PROGRESS_VISIBILITY_OFF);
4846 setTitle(R.string.tab_picker_title);
4847 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004848 // Make the menu empty until the animation completes.
4849 mMenuState = EMPTY_MENU;
4850 }
4851
Leon Scrogginse4b3bda2009-06-09 15:46:41 -04004852 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004853 WebView current = mTabControl.getCurrentWebView();
4854 if (current == null) {
4855 return;
4856 }
4857 Intent intent = new Intent(this,
4858 CombinedBookmarkHistoryActivity.class);
4859 String title = current.getTitle();
4860 String url = current.getUrl();
4861 // Just in case the user opens bookmarks before a page finishes loading
4862 // so the current history item, and therefore the page, is null.
4863 if (null == url) {
4864 url = mLastEnteredUrl;
4865 // This can happen.
4866 if (null == url) {
4867 url = mSettings.getHomePage();
4868 }
4869 }
4870 // In case the web page has not yet received its associated title.
4871 if (title == null) {
4872 title = url;
4873 }
4874 intent.putExtra("title", title);
4875 intent.putExtra("url", url);
4876 intent.putExtra("maxTabsOpen",
4877 mTabControl.getTabCount() >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004878 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004879 if (startWithHistory) {
4880 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4881 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4882 }
4883 startActivityForResult(intent, COMBO_PAGE);
4884 }
4885
4886 // Called when loading from context menu or LOAD_URL message
4887 private void loadURL(WebView view, String url) {
4888 // In case the user enters nothing.
4889 if (url != null && url.length() != 0 && view != null) {
4890 url = smartUrlFilter(url);
4891 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4892 view.loadUrl(url);
4893 }
4894 }
4895 }
4896
The Android Open Source Project0c908882009-03-03 19:32:16 -08004897 private String smartUrlFilter(Uri inUri) {
4898 if (inUri != null) {
4899 return smartUrlFilter(inUri.toString());
4900 }
4901 return null;
4902 }
4903
4904
4905 // get window count
4906
4907 int getWindowCount(){
4908 if(mTabControl != null){
4909 return mTabControl.getTabCount();
4910 }
4911 return 0;
4912 }
4913
Feng Qianb34f87a2009-03-24 21:27:26 -07004914 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004915 "(?i)" + // switch on case insensitive matching
4916 "(" + // begin group for schema
4917 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004918 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004919 ")" +
4920 "(.*)" );
4921
4922 /**
4923 * Attempts to determine whether user input is a URL or search
4924 * terms. Anything with a space is passed to search.
4925 *
4926 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4927 * "Http://" converts to "http://"
4928 *
4929 * @return Original or modified URL
4930 *
4931 */
4932 String smartUrlFilter(String url) {
4933
4934 String inUrl = url.trim();
4935 boolean hasSpace = inUrl.indexOf(' ') != -1;
4936
4937 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4938 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004939 // force scheme to lowercase
4940 String scheme = matcher.group(1);
4941 String lcScheme = scheme.toLowerCase();
4942 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004943 inUrl = lcScheme + matcher.group(2);
4944 }
4945 if (hasSpace) {
4946 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004947 }
4948 return inUrl;
4949 }
4950 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004951 // FIXME: Is this the correct place to add to searches?
4952 // what if someone else calls this function?
4953 int shortcut = parseUrlShortcut(inUrl);
4954 if (shortcut != SHORTCUT_INVALID) {
4955 Browser.addSearchUrl(mResolver, inUrl);
4956 String query = inUrl.substring(2);
4957 switch (shortcut) {
4958 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004959 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004960 case SHORTCUT_WIKIPEDIA_SEARCH:
4961 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4962 case SHORTCUT_DICTIONARY_SEARCH:
4963 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4964 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004965 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004966 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004967 }
4968 }
4969 } else {
4970 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4971 return URLUtil.guessUrl(inUrl);
4972 }
4973 }
4974
4975 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004976 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004977 }
4978
Ben Murdochbff2d602009-07-01 20:19:05 +01004979 /* package */ void setShouldShowErrorConsole(boolean flag) {
4980 if (flag == mShouldShowErrorConsole) {
4981 // Nothing to do.
4982 return;
4983 }
4984
4985 mShouldShowErrorConsole = flag;
4986
4987 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4988
4989 if (flag) {
4990 // Setting the show state of the console will cause it's the layout to be inflated.
4991 if (errorConsole.numberOfErrors() > 0) {
4992 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4993 } else {
4994 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4995 }
4996
4997 // Now we can add it to the main view.
4998 mErrorConsoleContainer.addView(errorConsole,
4999 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
5000 ViewGroup.LayoutParams.WRAP_CONTENT));
5001 } else {
5002 mErrorConsoleContainer.removeView(errorConsole);
5003 }
5004
5005 }
5006
The Android Open Source Project0c908882009-03-03 19:32:16 -08005007 private final static int LOCK_ICON_UNSECURE = 0;
5008 private final static int LOCK_ICON_SECURE = 1;
5009 private final static int LOCK_ICON_MIXED = 2;
5010
5011 private int mLockIconType = LOCK_ICON_UNSECURE;
5012 private int mPrevLockType = LOCK_ICON_UNSECURE;
5013
5014 private BrowserSettings mSettings;
5015 private TabControl mTabControl;
5016 private ContentResolver mResolver;
5017 private FrameLayout mContentView;
5018 private ImageGrid mTabOverview;
Andrei Popescuadc008d2009-06-26 14:11:30 +01005019 private View mCustomView;
5020 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01005021 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005022
5023 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
5024 // view, we should rewrite this.
5025 private int mCurrentMenuState = 0;
5026 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01005027 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005028 private static final int EMPTY_MENU = -1;
5029 private Menu mMenu;
5030
5031 private FindDialog mFindDialog;
5032 // Used to prevent chording to result in firing two shortcuts immediately
5033 // one after another. Fixes bug 1211714.
5034 boolean mCanChord;
5035
5036 private boolean mInLoad;
5037 private boolean mIsNetworkUp;
5038
5039 private boolean mPageStarted;
5040 private boolean mActivityInPause = true;
5041
5042 private boolean mMenuIsDown;
5043
5044 private final KeyTracker mKeyTracker = new KeyTracker(this);
5045
5046 // As trackball doesn't send repeat down, we have to track it ourselves
5047 private boolean mTrackTrackball;
5048
5049 private static boolean mInTrace;
5050
5051 // Performance probe
5052 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
5053 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
5054 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
5055 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
5056 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
5057 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
5058 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
5059 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
5060 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
5061 };
5062
5063 private long mStart;
5064 private long mProcessStart;
5065 private long mUserStart;
5066 private long mSystemStart;
5067 private long mIdleStart;
5068 private long mIrqStart;
5069
5070 private long mUiStart;
5071
5072 private Drawable mMixLockIcon;
5073 private Drawable mSecLockIcon;
5074 private Drawable mGenericFavicon;
5075
5076 /* hold a ref so we can auto-cancel if necessary */
5077 private AlertDialog mAlertDialog;
5078
5079 // Wait for credentials before loading google.com
5080 private ProgressDialog mCredsDlg;
5081
5082 // The up-to-date URL and title (these can be different from those stored
5083 // in WebView, since it takes some time for the information in WebView to
5084 // get updated)
5085 private String mUrl;
5086 private String mTitle;
5087
5088 // As PageInfo has different style for landscape / portrait, we have
5089 // to re-open it when configuration changed
5090 private AlertDialog mPageInfoDialog;
5091 private TabControl.Tab mPageInfoView;
5092 // If the Page-Info dialog is launched from the SSL-certificate-on-error
5093 // dialog, we should not just dismiss it, but should get back to the
5094 // SSL-certificate-on-error dialog. This flag is used to store this state
5095 private Boolean mPageInfoFromShowSSLCertificateOnError;
5096
5097 // as SSLCertificateOnError has different style for landscape / portrait,
5098 // we have to re-open it when configuration changed
5099 private AlertDialog mSSLCertificateOnErrorDialog;
5100 private WebView mSSLCertificateOnErrorView;
5101 private SslErrorHandler mSSLCertificateOnErrorHandler;
5102 private SslError mSSLCertificateOnErrorError;
5103
5104 // as SSLCertificate has different style for landscape / portrait, we
5105 // have to re-open it when configuration changed
5106 private AlertDialog mSSLCertificateDialog;
5107 private TabControl.Tab mSSLCertificateView;
5108
5109 // as HttpAuthentication has different style for landscape / portrait, we
5110 // have to re-open it when configuration changed
5111 private AlertDialog mHttpAuthenticationDialog;
5112 private HttpAuthHandler mHttpAuthHandler;
5113
5114 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
5115 new FrameLayout.LayoutParams(
5116 ViewGroup.LayoutParams.FILL_PARENT,
5117 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01005118 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
5119 new FrameLayout.LayoutParams(
5120 ViewGroup.LayoutParams.FILL_PARENT,
5121 ViewGroup.LayoutParams.FILL_PARENT,
5122 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07005123 // Google search
5124 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08005125 // Wikipedia search
5126 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
5127 // Dictionary search
5128 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
5129 // Google Mobile Local search
5130 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
5131
5132 final static String QUERY_PLACE_HOLDER = "%s";
5133
5134 // "source" parameter for Google search through search key
5135 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
5136 // "source" parameter for Google search through goto menu
5137 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
5138 // "source" parameter for Google search through simplily type
5139 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
5140 // "source" parameter for Google search suggested by the browser
5141 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
5142 // "source" parameter for Google search from unknown source
5143 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
5144
5145 private final static String LOGTAG = "browser";
5146
5147 private TabListener mTabListener;
5148
5149 private String mLastEnteredUrl;
5150
5151 private PowerManager.WakeLock mWakeLock;
5152 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
5153
5154 private Toast mStopToast;
5155
Leon Scroggins81db3662009-06-04 17:45:11 -04005156 private TitleBar mTitleBar;
5157
Ben Murdochbff2d602009-07-01 20:19:05 +01005158 private LinearLayout mErrorConsoleContainer = null;
5159 private boolean mShouldShowErrorConsole = false;
5160
The Android Open Source Project0c908882009-03-03 19:32:16 -08005161 // Used during animations to prevent other animations from being triggered.
5162 // A count is used since the animation to and from the Window overview can
5163 // overlap. A count of 0 means no animation where a count of > 0 means
5164 // there are animations in progress.
5165 private int mAnimationCount;
5166
5167 // As the ids are dynamically created, we can't guarantee that they will
5168 // be in sequence, so this static array maps ids to a window number.
5169 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
5170 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
5171 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
5172 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
5173
5174 // monitor platform changes
5175 private IntentFilter mNetworkStateChangedFilter;
5176 private BroadcastReceiver mNetworkStateIntentReceiver;
5177
Grace Klobab4da0ad2009-05-14 14:45:40 -07005178 private BroadcastReceiver mPackageInstallationReceiver;
5179
The Android Open Source Project0c908882009-03-03 19:32:16 -08005180 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01005181 final static int COMBO_PAGE = 1;
5182 final static int DOWNLOAD_PAGE = 2;
5183 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005184
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005185 /**
5186 * A UrlData class to abstract how the content will be set to WebView.
5187 * This base class uses loadUrl to show the content.
5188 */
5189 private static class UrlData {
5190 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07005191 byte[] mPostData;
5192
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005193 UrlData(String url) {
5194 this.mUrl = url;
5195 }
Grace Kloba60e095c2009-06-16 11:50:55 -07005196
5197 void setPostData(byte[] postData) {
5198 mPostData = postData;
5199 }
5200
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005201 boolean isEmpty() {
5202 return mUrl == null || mUrl.length() == 0;
5203 }
5204
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005205 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07005206 if (mPostData != null) {
5207 webView.postUrl(mUrl, mPostData);
5208 } else {
5209 webView.loadUrl(mUrl);
5210 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005211 }
5212 };
5213
5214 /**
5215 * A subclass of UrlData class that can display inlined content using
5216 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
5217 */
5218 private static class InlinedUrlData extends UrlData {
5219 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
5220 super(failUrl);
5221 mInlined = inlined;
5222 mMimeType = mimeType;
5223 mEncoding = encoding;
5224 }
5225 String mMimeType;
5226 String mInlined;
5227 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005228 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005229 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01005230 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005231 }
5232
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005233 @Override
5234 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005235 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
5236 }
5237 }
5238
5239 private static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08005240}