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