1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
|
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko;
import org.mozilla.gecko.DataReportingNotification;
import org.mozilla.gecko.background.announcements.AnnouncementsBroadcastService;
import org.mozilla.gecko.db.BrowserDB;
import org.mozilla.gecko.gfx.BitmapUtils;
import org.mozilla.gecko.gfx.Layer;
import org.mozilla.gecko.gfx.LayerView;
import org.mozilla.gecko.gfx.PluginLayer;
import org.mozilla.gecko.menu.GeckoMenu;
import org.mozilla.gecko.menu.GeckoMenuInflater;
import org.mozilla.gecko.menu.MenuPanel;
import org.mozilla.gecko.health.BrowserHealthRecorder;
import org.mozilla.gecko.health.BrowserHealthRecorder.SessionInformation;
import org.mozilla.gecko.updater.UpdateService;
import org.mozilla.gecko.updater.UpdateServiceHelper;
import org.mozilla.gecko.util.EventDispatcher;
import org.mozilla.gecko.util.GeckoEventListener;
import org.mozilla.gecko.util.GeckoEventResponder;
import org.mozilla.gecko.util.HardwareUtils;
import org.mozilla.gecko.util.ThreadUtils;
import org.mozilla.gecko.util.UiAsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.location.LocationListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Base64;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
abstract public class GeckoApp
extends GeckoActivity
implements GeckoEventListener, SensorEventListener, LocationListener,
Tabs.OnTabsChangedListener, GeckoEventResponder,
GeckoMenu.Callback, GeckoMenu.MenuPresenter,
ContextGetter, GeckoAppShell.GeckoInterface
{
private static final String LOGTAG = "GeckoApp";
private static enum StartupAction {
NORMAL, /* normal application start */
URL, /* launched with a passed URL */
PREFETCH /* launched with a passed URL that we prefetch */
}
public static final String ACTION_ALERT_CALLBACK = "org.mozilla.gecko.ACTION_ALERT_CALLBACK";
public static final String ACTION_WEBAPP_PREFIX = "org.mozilla.gecko.WEBAPP";
public static final String ACTION_DEBUG = "org.mozilla.gecko.DEBUG";
public static final String ACTION_BOOKMARK = "org.mozilla.gecko.BOOKMARK";
public static final String ACTION_LOAD = "org.mozilla.gecko.LOAD";
public static final String ACTION_LAUNCH_SETTINGS = "org.mozilla.gecko.SETTINGS";
public static final String ACTION_INIT_PW = "org.mozilla.gecko.INIT_PW";
public static final String SAVED_STATE_INTENT_HANDLED = "intentHandled";
public static final String SAVED_STATE_IN_BACKGROUND = "inBackground";
public static final String SAVED_STATE_PRIVATE_SESSION = "privateSession";
public static final String PREFS_NAME = "GeckoApp";
public static final String PREFS_OOM_EXCEPTION = "OOMException";
public static final String PREFS_WAS_STOPPED = "wasStopped";
public static final String PREFS_CRASHED = "crashed";
static public final int RESTORE_NONE = 0;
static public final int RESTORE_OOM = 1;
static public final int RESTORE_CRASH = 2;
protected RelativeLayout mMainLayout;
protected RelativeLayout mGeckoLayout;
public View getView() { return mGeckoLayout; }
private View mCameraView;
private OrientationEventListener mCameraOrientationEventListener;
public List<GeckoAppShell.AppStateListener> mAppStateListeners;
private static GeckoApp sAppContext;
protected MenuPanel mMenuPanel;
protected Menu mMenu;
private static GeckoThread sGeckoThread;
private GeckoProfile mProfile;
public static int mOrientation;
protected boolean mIsRestoringActivity;
private boolean mIntentHandled;
private String mCurrentResponse = "";
public static boolean sIsUsingCustomProfile = false;
private PromptService mPromptService;
private TextSelection mTextSelection;
protected DoorHangerPopup mDoorHangerPopup;
protected FormAssistPopup mFormAssistPopup;
protected TabsPanel mTabsPanel;
// Handles notification messages from javascript
protected NotificationHelper mNotificationHelper;
protected LayerView mLayerView;
private AbsoluteLayout mPluginContainer;
private FullScreenHolder mFullScreenPluginContainer;
private View mFullScreenPluginView;
private HashMap<String, PowerManager.WakeLock> mWakeLocks = new HashMap<String, PowerManager.WakeLock>();
protected int mRestoreMode = RESTORE_NONE;
protected boolean mInitialized = false;
private Telemetry.Timer mJavaUiStartupTimer;
private Telemetry.Timer mGeckoReadyStartupTimer;
private String mPrivateBrowsingSession;
private volatile BrowserHealthRecorder mHealthRecorder = null;
abstract public int getLayout();
abstract public boolean hasTabsSideBar();
abstract protected String getDefaultProfileName();
private static final String RESTARTER_ACTION = "org.mozilla.gecko.restart";
private static final String RESTARTER_CLASS = "org.mozilla.gecko.Restarter";
@SuppressWarnings("serial")
class SessionRestoreException extends Exception {
public SessionRestoreException(Exception e) {
super(e);
}
public SessionRestoreException(String message) {
super(message);
}
}
void toggleChrome(final boolean aShow) { }
void focusChrome() { }
public Context getContext() {
return sAppContext;
}
public Activity getActivity() {
return this;
}
public LocationListener getLocationListener() {
return this;
}
public SensorEventListener getSensorEventListener() {
return this;
}
public static SharedPreferences getAppSharedPreferences() {
return GeckoApp.sAppContext.getSharedPreferences(PREFS_NAME, 0);
}
public View getCameraView() {
return mCameraView;
}
public void addAppStateListener(GeckoAppShell.AppStateListener listener) {
mAppStateListeners.add(listener);
}
public void removeAppStateListener(GeckoAppShell.AppStateListener listener) {
mAppStateListeners.remove(listener);
}
public FormAssistPopup getFormAssistPopup() {
return mFormAssistPopup;
}
@Override
public void onTabChanged(Tab tab, Tabs.TabEvents msg, Object data) {
// When a tab is closed, it is always unselected first.
// When a tab is unselected, another tab is always selected first.
switch(msg) {
case UNSELECTED:
hidePlugins(tab);
break;
case LOCATION_CHANGE:
// We only care about location change for the selected tab.
if (!Tabs.getInstance().isSelectedTab(tab))
break;
// Fall through...
case SELECTED:
invalidateOptionsMenu();
if (mFormAssistPopup != null)
mFormAssistPopup.hide();
break;
case LOADED:
// Sync up the layer view and the tab if the tab is
// currently displayed.
LayerView layerView = mLayerView;
if (layerView != null && Tabs.getInstance().isSelectedTab(tab))
layerView.setBackgroundColor(tab.getBackgroundColor());
break;
case DESKTOP_MODE_CHANGE:
if (Tabs.getInstance().isSelectedTab(tab))
invalidateOptionsMenu();
break;
}
}
public void refreshChrome() { }
@Override
public void invalidateOptionsMenu() {
if (mMenu == null)
return;
onPrepareOptionsMenu(mMenu);
if (Build.VERSION.SDK_INT >= 11)
super.invalidateOptionsMenu();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
mMenu = menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.gecko_app_menu, mMenu);
return true;
}
@Override
public MenuInflater getMenuInflater() {
if (Build.VERSION.SDK_INT >= 11)
return new GeckoMenuInflater(this);
else
return super.getMenuInflater();
}
public MenuPanel getMenuPanel() {
return mMenuPanel;
}
@Override
public boolean onMenuItemSelected(MenuItem item) {
return onOptionsItemSelected(item);
}
@Override
public void openMenu() {
openOptionsMenu();
}
@Override
public void showMenu(View menu) {
// Hide the menu only if we are showing the MenuPopup.
if (!HardwareUtils.hasMenuButton())
closeMenu();
mMenuPanel.removeAllViews();
mMenuPanel.addView(menu);
openOptionsMenu();
}
@Override
public void closeMenu() {
closeOptionsMenu();
}
@Override
public View onCreatePanelView(int featureId) {
if (Build.VERSION.SDK_INT >= 11 && featureId == Window.FEATURE_OPTIONS_PANEL) {
if (mMenuPanel == null) {
mMenuPanel = new MenuPanel(this, null);
} else {
// Prepare the panel everytime before showing the menu.
onPreparePanel(featureId, mMenuPanel, mMenu);
}
return mMenuPanel;
}
return super.onCreatePanelView(featureId);
}
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (Build.VERSION.SDK_INT >= 11 && featureId == Window.FEATURE_OPTIONS_PANEL) {
if (mMenuPanel == null) {
mMenuPanel = (MenuPanel) onCreatePanelView(featureId);
}
GeckoMenu gMenu = new GeckoMenu(this, null);
gMenu.setCallback(this);
gMenu.setMenuPresenter(this);
menu = gMenu;
mMenuPanel.addView(gMenu);
return onCreateOptionsMenu(menu);
}
return super.onCreatePanelMenu(featureId, menu);
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (Build.VERSION.SDK_INT >= 11 && featureId == Window.FEATURE_OPTIONS_PANEL)
return onPrepareOptionsMenu(menu);
return super.onPreparePanel(featureId, view, menu);
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
// exit full-screen mode whenever the menu is opened
if (mLayerView != null && mLayerView.isFullScreen()) {
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("FullScreen:Exit", null));
}
if (Build.VERSION.SDK_INT >= 11 && featureId == Window.FEATURE_OPTIONS_PANEL) {
if (mMenu == null) {
onCreatePanelMenu(featureId, menu);
onPreparePanel(featureId, mMenuPanel, mMenu);
}
// Scroll custom menu to the top
if (mMenuPanel != null)
mMenuPanel.scrollTo(0, 0);
return true;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.quit:
if (GeckoThread.checkAndSetLaunchState(GeckoThread.LaunchState.GeckoRunning, GeckoThread.LaunchState.GeckoExiting)) {
GeckoAppShell.notifyGeckoOfEvent(GeckoEvent.createBroadcastEvent("Browser:Quit", null));
} else {
System.exit(0);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onOptionsMenuClosed(Menu menu) {
if (Build.VERSION.SDK_INT >= 11) {
mMenuPanel.removeAllViews();
mMenuPanel.addView((GeckoMenu) mMenu);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Handle hardware menu key presses separately so that we can show a custom menu in some cases.
if (keyCode == KeyEvent.KEYCODE_MENU) {
openOptionsMenu();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (outState == null)
outState = new Bundle();
outState.putBoolean(SAVED_STATE_IN_BACKGROUND, isApplicationInBackground());
outState.putString(SAVED_STATE_PRIVATE_SESSION, mPrivateBrowsingSession);
// Bug 896992 - Replace intent action with ACTION_MAIN on restart.
if (mIntentHandled) {
outState.putBoolean(SAVED_STATE_INTENT_HANDLED, true);
}
}
void handleFaviconRequest(final String url) {
(new UiAsyncTask<Void, Void, String>(ThreadUtils.getBackgroundHandler()) {
@Override
public String doInBackground(Void... params) {
return Favicons.getInstance().getFaviconUrlForPageUrl(url);
}
@Override
public void onPostExecute(String faviconUrl) {
JSONObject args = new JSONObject();
if (faviconUrl != null) {
try {
args.put("url", url);
args.put("faviconUrl", faviconUrl);
} catch (JSONException e) {
Log.w(LOGTAG, "Error building JSON favicon arguments.", e);
}
}
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Reader:FaviconReturn", args.toString()));
}
}).execute();
}
void handleClearHistory() {
BrowserDB.clearHistory(getContentResolver());
}
public void addTab() { }
public void addPrivateTab() { }
public void showNormalTabs() { }
public void showPrivateTabs() { }
public void showRemoteTabs() { }
private void showTabs(TabsPanel.Panel panel) { }
public void hideTabs() { }
/**
* Close the tab UI indirectly (not as the result of a direct user
* action). This does not force the UI to close; for example in Firefox
* tablet mode it will remain open unless the user explicitly closes it.
*
* @return True if the tab UI was hidden.
*/
public boolean autoHideTabs() { return false; }
public boolean areTabsShown() { return false; }
@Override
public void handleMessage(String event, JSONObject message) {
try {
if (event.equals("Toast:Show")) {
final String msg = message.getString("message");
final String duration = message.getString("duration");
handleShowToast(msg, duration);
} else if (event.equals("log")) {
// generic log listener
final String msg = message.getString("msg");
Log.d(LOGTAG, "Log: " + msg);
} else if (event.equals("Reader:FaviconRequest")) {
final String url = message.getString("url");
handleFaviconRequest(url);
} else if (event.equals("Reader:GoToReadingList")) {
showReadingList();
} else if (event.equals("Gecko:Ready")) {
mGeckoReadyStartupTimer.stop();
geckoConnected();
// This method is already running on the background thread, so we
// know that mHealthRecorder will exist. That doesn't stop us being
// paranoid.
// This method is cheap, so don't spawn a new runnable.
final BrowserHealthRecorder rec = mHealthRecorder;
if (rec != null) {
rec.recordGeckoStartupTime(mGeckoReadyStartupTimer.getElapsed());
}
} else if (event.equals("ToggleChrome:Hide")) {
toggleChrome(false);
} else if (event.equals("ToggleChrome:Show")) {
toggleChrome(true);
} else if (event.equals("ToggleChrome:Focus")) {
focusChrome();
} else if (event.equals("DOMFullScreen:Start")) {
// Local ref to layerView for thread safety
LayerView layerView = mLayerView;
if (layerView != null) {
layerView.setFullScreen(true);
}
} else if (event.equals("DOMFullScreen:Stop")) {
// Local ref to layerView for thread safety
LayerView layerView = mLayerView;
if (layerView != null) {
layerView.setFullScreen(false);
}
} else if (event.equals("Permissions:Data")) {
String host = message.getString("host");
JSONArray permissions = message.getJSONArray("permissions");
showSiteSettingsDialog(host, permissions);
} else if (event.equals("Tab:ViewportMetadata")) {
int tabId = message.getInt("tabID");
Tab tab = Tabs.getInstance().getTab(tabId);
if (tab == null)
return;
tab.setZoomConstraints(new ZoomConstraints(message));
tab.setIsRTL(message.getBoolean("isRTL"));
// Sync up the layer view and the tab if the tab is currently displayed.
LayerView layerView = mLayerView;
if (layerView != null && Tabs.getInstance().isSelectedTab(tab)) {
layerView.setZoomConstraints(tab.getZoomConstraints());
layerView.setIsRTL(tab.getIsRTL());
}
} else if (event.equals("Session:StatePurged")) {
onStatePurged();
} else if (event.equals("Bookmark:Insert")) {
final String url = message.getString("url");
final String title = message.getString("title");
final Context context = this;
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, R.string.bookmark_added, Toast.LENGTH_SHORT).show();
ThreadUtils.postToBackgroundThread(new Runnable() {
@Override
public void run() {
BrowserDB.addBookmark(getContentResolver(), title, url);
}
});
}
});
} else if (event.equals("Accessibility:Event")) {
GeckoAccessibility.sendAccessibilityEvent(message);
} else if (event.equals("Accessibility:Ready")) {
GeckoAccessibility.updateAccessibilitySettings(this);
} else if (event.equals("Shortcut:Remove")) {
final String url = message.getString("url");
final String origin = message.getString("origin");
final String title = message.getString("title");
final String type = message.getString("shortcutType");
GeckoAppShell.removeShortcut(title, url, origin, type);
} else if (event.equals("WebApps:Open")) {
String manifestURL = message.getString("manifestURL");
String origin = message.getString("origin");
Intent intent = GeckoAppShell.getWebAppIntent(manifestURL, origin, "", null);
if (intent == null)
return;
startActivity(intent);
} else if (event.equals("WebApps:Install")) {
String name = message.getString("name");
String manifestURL = message.getString("manifestURL");
String iconURL = message.getString("iconURL");
String origin = message.getString("origin");
// preInstallWebapp will return a File object pointing to the profile directory of the webapp
mCurrentResponse = GeckoAppShell.preInstallWebApp(name, manifestURL, origin).toString();
GeckoAppShell.postInstallWebApp(name, manifestURL, origin, iconURL);
} else if (event.equals("WebApps:PreInstall")) {
String name = message.getString("name");
String manifestURL = message.getString("manifestURL");
String origin = message.getString("origin");
// preInstallWebapp will return a File object pointing to the profile directory of the webapp
mCurrentResponse = GeckoAppShell.preInstallWebApp(name, manifestURL, origin).toString();
} else if (event.equals("WebApps:PostInstall")) {
String name = message.getString("name");
String manifestURL = message.getString("manifestURL");
String iconURL = message.getString("iconURL");
String origin = message.getString("origin");
GeckoAppShell.postInstallWebApp(name, manifestURL, origin, iconURL);
} else if (event.equals("WebApps:Uninstall")) {
String origin = message.getString("origin");
GeckoAppShell.uninstallWebApp(origin);
} else if (event.equals("Share:Text")) {
String text = message.getString("text");
GeckoAppShell.openUriExternal(text, "text/plain", "", "", Intent.ACTION_SEND, "");
} else if (event.equals("Share:Image")) {
String src = message.getString("url");
String type = message.getString("mime");
GeckoAppShell.shareImage(src, type);
} else if (event.equals("Wallpaper:Set")) {
String src = message.getString("url");
setImageAsWallpaper(src);
} else if (event.equals("Sanitize:ClearHistory")) {
handleClearHistory();
} else if (event.equals("Update:Check")) {
startService(new Intent(UpdateServiceHelper.ACTION_CHECK_FOR_UPDATE, null, this, UpdateService.class));
} else if (event.equals("Update:Download")) {
startService(new Intent(UpdateServiceHelper.ACTION_DOWNLOAD_UPDATE, null, this, UpdateService.class));
} else if (event.equals("Update:Install")) {
startService(new Intent(UpdateServiceHelper.ACTION_APPLY_UPDATE, null, this, UpdateService.class));
} else if (event.equals("PrivateBrowsing:Data")) {
// null strings return "null" (http://code.google.com/p/android/issues/detail?id=13830)
if (message.isNull("session")) {
mPrivateBrowsingSession = null;
} else {
mPrivateBrowsingSession = message.getString("session");
}
} else if (event.equals("Contact:Add")) {
if (!message.isNull("email")) {
Uri contactUri = Uri.parse(message.getString("email"));
Intent i = new Intent(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT, contactUri);
startActivity(i);
} else if (!message.isNull("phone")) {
Uri contactUri = Uri.parse(message.getString("phone"));
Intent i = new Intent(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT, contactUri);
startActivity(i);
} else {
// something went wrong.
Log.e(LOGTAG, "Received Contact:Add message with no email nor phone number");
}
}
} catch (Exception e) {
Log.e(LOGTAG, "Exception handling message \"" + event + "\":", e);
}
}
public String getResponse(JSONObject origMessage) {
String res = mCurrentResponse;
mCurrentResponse = "";
return res;
}
void onStatePurged() { }
/**
* @param aPermissions
* Array of JSON objects to represent site permissions.
* Example: { type: "offline-app", setting: "Store Offline Data", value: "Allow" }
*/
private void showSiteSettingsDialog(String aHost, JSONArray aPermissions) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
View customTitleView = getLayoutInflater().inflate(R.layout.site_setting_title, null);
((TextView) customTitleView.findViewById(R.id.title)).setText(R.string.site_settings_title);
((TextView) customTitleView.findViewById(R.id.host)).setText(aHost);
builder.setCustomTitle(customTitleView);
// If there are no permissions to clear, show the user a message about that.
// In the future, we want to disable the menu item if there are no permissions to clear.
if (aPermissions.length() == 0) {
builder.setMessage(R.string.site_settings_no_settings);
} else {
ArrayList <HashMap<String, String>> itemList = new ArrayList <HashMap<String, String>>();
for (int i = 0; i < aPermissions.length(); i++) {
try {
JSONObject permObj = aPermissions.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("setting", permObj.getString("setting"));
map.put("value", permObj.getString("value"));
itemList.add(map);
} catch (JSONException e) {
Log.w(LOGTAG, "Exception populating settings items.", e);
}
}
// setMultiChoiceItems doesn't support using an adapter, so we're creating a hack with
// setSingleChoiceItems and changing the choiceMode below when we create the dialog
builder.setSingleChoiceItems(new SimpleAdapter(
GeckoApp.this,
itemList,
R.layout.site_setting_item,
new String[] { "setting", "value" },
new int[] { R.id.setting, R.id.value }
), -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) { }
});
builder.setPositiveButton(R.string.site_settings_clear, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
ListView listView = ((AlertDialog) dialog).getListView();
SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
// An array of the indices of the permissions we want to clear
JSONArray permissionsToClear = new JSONArray();
for (int i = 0; i < checkedItemPositions.size(); i++)
if (checkedItemPositions.get(i))
permissionsToClear.put(i);
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent(
"Permissions:Clear", permissionsToClear.toString()));
}
});
}
builder.setNegativeButton(R.string.site_settings_cancel, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
Dialog dialog = builder.create();
dialog.show();
ListView listView = ((AlertDialog) dialog).getListView();
if (listView != null) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
int listSize = listView.getAdapter().getCount();
for (int i = 0; i < listSize; i++)
listView.setItemChecked(i, true);
}
}
});
}
public void showToast(final int resId, final int duration) {
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(GeckoApp.this, resId, duration).show();
}
});
}
void handleShowToast(final String message, final String duration) {
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
Toast toast;
if (duration.equals("long"))
toast = Toast.makeText(GeckoApp.this, message, Toast.LENGTH_LONG);
else
toast = Toast.makeText(GeckoApp.this, message, Toast.LENGTH_SHORT);
toast.show();
}
});
}
private void addFullScreenPluginView(View view) {
if (mFullScreenPluginView != null) {
Log.w(LOGTAG, "Already have a fullscreen plugin view");
return;
}
setFullScreen(true);
view.setWillNotDraw(false);
if (view instanceof SurfaceView) {
((SurfaceView) view).setZOrderOnTop(true);
}
mFullScreenPluginContainer = new FullScreenHolder(this);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT,
Gravity.CENTER);
mFullScreenPluginContainer.addView(view, layoutParams);
FrameLayout decor = (FrameLayout)getWindow().getDecorView();
decor.addView(mFullScreenPluginContainer, layoutParams);
mFullScreenPluginView = view;
}
public void addPluginView(final View view, final Rect rect, final boolean isFullScreen) {
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
Tabs tabs = Tabs.getInstance();
Tab tab = tabs.getSelectedTab();
if (isFullScreen) {
addFullScreenPluginView(view);
return;
}
PluginLayer layer = (PluginLayer) tab.getPluginLayer(view);
if (layer == null) {
layer = new PluginLayer(view, rect, mLayerView.getRenderer().getMaxTextureSize());
tab.addPluginLayer(view, layer);
} else {
layer.reset(rect);
layer.setVisible(true);
}
mLayerView.addLayer(layer);
}
});
}
private void removeFullScreenPluginView(View view) {
if (mFullScreenPluginView == null) {
Log.w(LOGTAG, "Don't have a fullscreen plugin view");
return;
}
if (mFullScreenPluginView != view) {
Log.w(LOGTAG, "Passed view is not the current full screen view");
return;
}
mFullScreenPluginContainer.removeView(mFullScreenPluginView);
// We need do do this on the next iteration in order to avoid
// a deadlock, see comment below in FullScreenHolder
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
mLayerView.show();
}
});
FrameLayout decor = (FrameLayout)getWindow().getDecorView();
decor.removeView(mFullScreenPluginContainer);
mFullScreenPluginView = null;
GeckoScreenOrientationListener.getInstance().unlockScreenOrientation();
setFullScreen(false);
}
public void removePluginView(final View view, final boolean isFullScreen) {
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
Tabs tabs = Tabs.getInstance();
Tab tab = tabs.getSelectedTab();
if (isFullScreen) {
removeFullScreenPluginView(view);
return;
}
PluginLayer layer = (PluginLayer) tab.removePluginLayer(view);
if (layer != null) {
layer.destroy();
}
}
});
}
private void setImageAsWallpaper(final String aSrc) {
final String progText = getString(R.string.wallpaper_progress);
final String successText = getString(R.string.wallpaper_success);
final String failureText = getString(R.string.wallpaper_fail);
final String fileName = aSrc.substring(aSrc.lastIndexOf("/") + 1);
final PendingIntent emptyIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
final AlertNotification notification = new AlertNotification(this, fileName.hashCode(),
R.drawable.alert_download, fileName, progText, System.currentTimeMillis(), null);
notification.setLatestEventInfo(this, fileName, progText, emptyIntent );
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.show();
new UiAsyncTask<Void, Void, Boolean>(ThreadUtils.getBackgroundHandler()) {
@Override
protected Boolean doInBackground(Void... params) {
WallpaperManager mgr = WallpaperManager.getInstance(GeckoApp.this);
if (mgr == null) {
return false;
}
// Determine the ideal width and height of the wallpaper
// for the device
int idealWidth = mgr.getDesiredMinimumWidth();
int idealHeight = mgr.getDesiredMinimumHeight();
// Sometimes WallpaperManager's getDesiredMinimum*() methods
// can return 0 if a Remote Exception occurs when calling the
// Wallpaper Service. So if that fails, we are calculating
// the ideal width and height from the device's display
// resolution (excluding the decorated area)
if (idealWidth <= 0 || idealHeight <= 0) {
int orientation;
Display defaultDisplay = getWindowManager().getDefaultDisplay();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
orientation = defaultDisplay.getRotation();
} else {
orientation = defaultDisplay.getOrientation();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Point size = new Point();
defaultDisplay.getSize(size);
// The ideal wallpaper width is always twice the size of
// display width
if (orientation == Surface.ROTATION_0 || orientation == Surface.ROTATION_270) {
idealWidth = size.x * 2;
idealHeight = size.y;
} else {
idealWidth = size.y;
idealHeight = size.x * 2;
}
} else {
if (orientation == Surface.ROTATION_0 || orientation == Surface.ROTATION_270) {
idealWidth = defaultDisplay.getWidth() * 2;
idealHeight = defaultDisplay.getHeight();
} else {
idealWidth = defaultDisplay.getHeight();
idealHeight = defaultDisplay.getWidth() * 2;
}
}
}
boolean isDataURI = aSrc.startsWith("data:");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap image = null;
InputStream is = null;
ByteArrayOutputStream os = null;
try{
if (isDataURI) {
int dataStart = aSrc.indexOf(',');
byte[] buf = Base64.decode(aSrc.substring(dataStart+1), Base64.DEFAULT);
BitmapUtils.decodeByteArray(buf, options);
options.inSampleSize = getBitmapSampleSize(options, idealWidth, idealHeight);
options.inJustDecodeBounds = false;
image = BitmapUtils.decodeByteArray(buf, options);
} else {
int byteRead;
byte[] buf = new byte[4192];
os = new ByteArrayOutputStream();
URL url = new URL(aSrc);
is = url.openStream();
// Cannot read from same stream twice. Also, InputStream from
// URL does not support reset. So converting to byte array
while((byteRead = is.read(buf)) != -1) {
os.write(buf, 0, byteRead);
}
byte[] imgBuffer = os.toByteArray();
BitmapUtils.decodeByteArray(imgBuffer, options);
options.inSampleSize = getBitmapSampleSize(options, idealWidth, idealHeight);
options.inJustDecodeBounds = false;
image = BitmapUtils.decodeByteArray(imgBuffer, options);
}
if(image != null) {
mgr.setBitmap(image);
return true;
} else {
return false;
}
} catch(OutOfMemoryError ome) {
Log.e(LOGTAG, "Out of Memory when converting to byte array", ome);
return false;
} catch(IOException ioe) {
Log.e(LOGTAG, "I/O Exception while setting wallpaper", ioe);
return false;
} finally {
if(is != null) {
try {
is.close();
} catch(IOException ioe) {
Log.w(LOGTAG, "I/O Exception while closing stream", ioe);
}
}
if(os != null) {
try {
os.close();
} catch(IOException ioe) {
Log.w(LOGTAG, "I/O Exception while closing stream", ioe);
}
}
}
}
@Override
protected void onPostExecute(Boolean success) {
notification.cancel();
notification.flags = 0;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
if(!success) {
notification.tickerText = failureText;
notification.setLatestEventInfo(GeckoApp.this, fileName, failureText, emptyIntent);
} else {
notification.tickerText = successText;
notification.setLatestEventInfo(GeckoApp.this, fileName, successText, emptyIntent);
}
notification.show();
}
}.execute();
}
private int getBitmapSampleSize(BitmapFactory.Options options, int idealWidth, int idealHeight) {
int width = options.outWidth;
int height = options.outHeight;
int inSampleSize = 1;
if (height > idealHeight || width > idealWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)idealHeight);
} else {
inSampleSize = Math.round((float)width / (float)idealWidth);
}
}
return inSampleSize;
}
private void hidePluginLayer(Layer layer) {
LayerView layerView = mLayerView;
layerView.removeLayer(layer);
layerView.requestRender();
}
private void showPluginLayer(Layer layer) {
LayerView layerView = mLayerView;
layerView.addLayer(layer);
layerView.requestRender();
}
public void requestRender() {
mLayerView.requestRender();
}
public void hidePlugins(Tab tab) {
for (Layer layer : tab.getPluginLayers()) {
if (layer instanceof PluginLayer) {
((PluginLayer) layer).setVisible(false);
}
hidePluginLayer(layer);
}
requestRender();
}
public void showPlugins() {
Tabs tabs = Tabs.getInstance();
Tab tab = tabs.getSelectedTab();
showPlugins(tab);
}
public void showPlugins(Tab tab) {
for (Layer layer : tab.getPluginLayers()) {
showPluginLayer(layer);
if (layer instanceof PluginLayer) {
((PluginLayer) layer).setVisible(true);
}
}
requestRender();
}
public void setFullScreen(final boolean fullscreen) {
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
// Hide/show the system notification bar
Window window = getWindow();
window.setFlags(fullscreen ?
WindowManager.LayoutParams.FLAG_FULLSCREEN : 0,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (Build.VERSION.SDK_INT >= 11)
window.getDecorView().setSystemUiVisibility(fullscreen ? 1 : 0);
}
});
}
/**
* Called when the activity is first created.
*
* Here we initialize all of our profile settings, Firefox Health Report,
* and other one-shot constructions.
**/
@Override
public void onCreate(Bundle savedInstanceState)
{
GeckoAppShell.registerGlobalExceptionHandler();
// Enable Android Strict Mode for developers' local builds (the "default" channel).
if ("default".equals(AppConstants.MOZ_UPDATE_CHANNEL)) {
enableStrictMode();
}
// The clock starts...now. Better hurry!
mJavaUiStartupTimer = new Telemetry.Timer("FENNEC_STARTUP_TIME_JAVAUI");
mGeckoReadyStartupTimer = new Telemetry.Timer("FENNEC_STARTUP_TIME_GECKOREADY");
String args = getIntent().getStringExtra("args");
String profileName = null;
String profilePath = null;
if (args != null) {
if (args.contains("-P")) {
Pattern p = Pattern.compile("(?:-P\\s*)(\\w*)(\\s*)");
Matcher m = p.matcher(args);
if (m.find()) {
profileName = m.group(1);
}
}
if (args.contains("-profile")) {
Pattern p = Pattern.compile("(?:-profile\\s*)(\\S*)(\\s*)");
Matcher m = p.matcher(args);
if (m.find()) {
profilePath = m.group(1);
}
if (profileName == null) {
profileName = getDefaultProfileName();
if (profileName == null)
profileName = "default";
}
GeckoApp.sIsUsingCustomProfile = true;
}
if (profileName != null || profilePath != null) {
mProfile = GeckoProfile.get(this, profileName, profilePath);
}
}
BrowserDB.initialize(getProfile().getName());
((GeckoApplication)getApplication()).initialize();
sAppContext = this;
GeckoAppShell.setContextGetter(this);
GeckoAppShell.setGeckoInterface(this);
ThreadUtils.setUiThread(Thread.currentThread(), new Handler());
Tabs.getInstance().attachToActivity(this);
Favicons.getInstance().attachToContext(this);
// When we detect a locale change, we need to restart Gecko, which
// actually means restarting the entire application. This logic should
// actually be handled elsewhere since GeckoApp may not be alive to
// handle this event if "Don't keep activities" is enabled (filed as
// bug 889082).
if (((GeckoApplication)getApplication()).needsRestart()) {
doRestart();
System.exit(0);
return;
}
if (sGeckoThread != null) {
// This happens when the GeckoApp activity is destroyed by Android
// without killing the entire application (see Bug 769269).
mIsRestoringActivity = true;
Telemetry.HistogramAdd("FENNEC_RESTORING_ACTIVITY", 1);
}
// Fix for Bug 830557 on Tegra boards running Froyo.
// This fix must be done before doing layout.
// Assume the bug is fixed in Gingerbread and up.
if (Build.VERSION.SDK_INT < 9) {
try {
Class<?> inputBindResultClass =
Class.forName("com.android.internal.view.InputBindResult");
java.lang.reflect.Field creatorField =
inputBindResultClass.getField("CREATOR");
Log.i(LOGTAG, "froyo startup fix: " + String.valueOf(creatorField.get(null)));
} catch (Exception e) {
Log.w(LOGTAG, "froyo startup fix failed", e);
}
}
LayoutInflater.from(this).setFactory(this);
super.onCreate(savedInstanceState);
mOrientation = getResources().getConfiguration().orientation;
setContentView(getLayout());
// Set up Gecko layout.
mGeckoLayout = (RelativeLayout) findViewById(R.id.gecko_layout);
mMainLayout = (RelativeLayout) findViewById(R.id.main_layout);
// Set up tabs panel.
mTabsPanel = (TabsPanel) findViewById(R.id.tabs_panel);
mNotificationHelper = new NotificationHelper(this);
// Check if the last run was exited due to a normal kill while
// we were in the background, or a more harsh kill while we were
// active.
mRestoreMode = getSessionRestoreState(savedInstanceState);
if (mRestoreMode == RESTORE_OOM) {
boolean wasInBackground =
savedInstanceState.getBoolean(SAVED_STATE_IN_BACKGROUND, false);
// Don't log OOM-kills if only one activity was destroyed. (For example
// from "Don't keep activities" on ICS)
if (!wasInBackground && !mIsRestoringActivity) {
Telemetry.HistogramAdd("FENNEC_WAS_KILLED", 1);
}
if (savedInstanceState.getBoolean(SAVED_STATE_INTENT_HANDLED, false)) {
Intent thisIntent = getIntent();
// Bug 896992 - This intent has already been handled, clear the intent action.
thisIntent.setAction(Intent.ACTION_MAIN);
setIntent(thisIntent);
// Persist this flag for reincarnations of this Activity Intent.
mIntentHandled = true;
}
mPrivateBrowsingSession = savedInstanceState.getString(SAVED_STATE_PRIVATE_SESSION);
}
// Perform background initialization.
ThreadUtils.postToBackgroundThread(new Runnable() {
@Override
public void run() {
final SharedPreferences prefs = GeckoApp.getAppSharedPreferences();
SessionInformation previousSession = SessionInformation.fromSharedPrefs(prefs);
if (previousSession.wasKilled()) {
Telemetry.HistogramAdd("FENNEC_WAS_KILLED", 1);
}
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(GeckoApp.PREFS_OOM_EXCEPTION, false);
// Put a flag to check if we got a normal `onSaveInstanceState`
// on exit, or if we were suddenly killed (crash or native OOM).
editor.putBoolean(GeckoApp.PREFS_WAS_STOPPED, false);
editor.commit();
// The lifecycle of mHealthRecorder is "shortly after onCreate"
// through "onDestroy" -- essentially the same as the lifecycle
// of the activity itself.
final String profilePath = getProfile().getDir().getAbsolutePath();
final EventDispatcher dispatcher = GeckoAppShell.getEventDispatcher();
Log.i(LOGTAG, "Creating BrowserHealthRecorder.");
mHealthRecorder = new BrowserHealthRecorder(GeckoApp.this, profilePath, dispatcher,
previousSession);
}
});
GeckoAppShell.setNotificationClient(makeNotificationClient());
}
protected void initializeChrome() {
mDoorHangerPopup = new DoorHangerPopup(this, null);
mPluginContainer = (AbsoluteLayout) findViewById(R.id.plugin_container);
mFormAssistPopup = (FormAssistPopup) findViewById(R.id.form_assist_popup);
if (mCameraView == null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
mCameraView = new SurfaceView(this);
((SurfaceView)mCameraView).getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
} else {
mCameraView = new TextureView(this);
}
}
if (mLayerView == null) {
LayerView layerView = (LayerView) findViewById(R.id.layer_view);
layerView.initializeView(GeckoAppShell.getEventDispatcher());
mLayerView = layerView;
GeckoAppShell.setLayerView(layerView);
// bind the GeckoEditable instance to the new LayerView
GeckoAppShell.notifyIMEContext(GeckoEditableListener.IME_STATE_DISABLED, "", "", "");
}
}
/**
* Loads the initial tab at Fennec startup.
*
* If Fennec was opened with an external URL, that URL will be loaded.
* Otherwise, unless there was a session restore, the default URL
* (about:home) be loaded.
*
* @param url External URL to load, or null to load the default URL
*/
protected void loadStartupTab(String url) {
if (url == null) {
if (mRestoreMode == RESTORE_NONE) {
// Show about:home if we aren't restoring previous session and
// there's no external URL
Tab tab = Tabs.getInstance().loadUrl("about:home", Tabs.LOADURL_NEW_TAB);
}
} else {
// If given an external URL, load it
int flags = Tabs.LOADURL_NEW_TAB | Tabs.LOADURL_USER_ENTERED | Tabs.LOADURL_EXTERNAL;
Tabs.getInstance().loadUrl(url, flags);
}
}
private void initialize() {
mInitialized = true;
invalidateOptionsMenu();
Intent intent = getIntent();
String action = intent.getAction();
String passedUri = null;
String uri = getURIFromIntent(intent);
if (uri != null && uri.length() > 0) {
passedUri = uri;
}
final boolean isExternalURL = passedUri != null && !passedUri.equals("about:home");
StartupAction startupAction;
if (isExternalURL) {
startupAction = StartupAction.URL;
} else {
startupAction = StartupAction.NORMAL;
}
// Start migrating as early as possible, can do this in
// parallel with Gecko load.
checkMigrateProfile();
Uri data = intent.getData();
if (data != null && "http".equals(data.getScheme())) {
startupAction = StartupAction.PREFETCH;
ThreadUtils.postToBackgroundThread(new PrefetchRunnable(data.toString()));
}
Tabs.registerOnTabsChangedListener(this);
initializeChrome();
// If we are doing a restore, read the session data and send it to Gecko
String restoreMessage = null;
if (mRestoreMode != RESTORE_NONE && !mIsRestoringActivity) {
try {
// restoreSessionTabs() will create simple tab stubs with the
// URL and title for each page, but we also need to restore
// session history. restoreSessionTabs() will inject the IDs
// of the tab stubs into the JSON data (which holds the session
// history). This JSON data is then sent to Gecko so session
// history can be restored for each tab.
restoreMessage = restoreSessionTabs(isExternalURL);
} catch (SessionRestoreException e) {
// If restore failed, do a normal startup
Log.e(LOGTAG, "An error occurred during restore", e);
mRestoreMode = RESTORE_NONE;
}
}
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Session:Restore", restoreMessage));
if (!mIsRestoringActivity) {
loadStartupTab(isExternalURL ? passedUri : null);
}
if (mRestoreMode == RESTORE_OOM) {
// If we successfully did an OOM restore, we now have tab stubs
// from the last session. Any future tabs should be animated.
Tabs.getInstance().notifyListeners(null, Tabs.TabEvents.RESTORED);
} else {
// Move the session file if it exists
getProfile().moveSessionFile();
}
if (mRestoreMode == RESTORE_NONE) {
Tabs.getInstance().notifyListeners(null, Tabs.TabEvents.RESTORED);
}
Telemetry.HistogramAdd("FENNEC_STARTUP_GECKOAPP_ACTION", startupAction.ordinal());
if (!mIsRestoringActivity) {
sGeckoThread = new GeckoThread(intent, passedUri);
ThreadUtils.setGeckoThread(sGeckoThread);
}
if (!ACTION_DEBUG.equals(action) &&
GeckoThread.checkAndSetLaunchState(GeckoThread.LaunchState.Launching, GeckoThread.LaunchState.Launched)) {
sGeckoThread.start();
} else if (ACTION_DEBUG.equals(action) &&
GeckoThread.checkAndSetLaunchState(GeckoThread.LaunchState.Launching, GeckoThread.LaunchState.WaitForDebugger)) {
ThreadUtils.getUiHandler().postDelayed(new Runnable() {
@Override
public void run() {
GeckoThread.setLaunchState(GeckoThread.LaunchState.Launching);
sGeckoThread.start();
}
}, 1000 * 5 /* 5 seconds */);
}
// Check if launched from data reporting notification.
if (ACTION_LAUNCH_SETTINGS.equals(action)) {
mIntentHandled = true;
Intent settingsIntent = new Intent(GeckoApp.this, GeckoPreferences.class);
// Copy extras.
settingsIntent.putExtras(intent);
startActivity(settingsIntent);
}
//app state callbacks
mAppStateListeners = new LinkedList<GeckoAppShell.AppStateListener>();
//register for events
registerEventListener("log");
registerEventListener("Reader:ListCountRequest");
registerEventListener("Reader:Added");
registerEventListener("Reader:Removed");
registerEventListener("Reader:Share");
registerEventListener("Reader:FaviconRequest");
registerEventListener("Reader:GoToReadingList");
registerEventListener("onCameraCapture");
registerEventListener("Menu:Add");
registerEventListener("Menu:Remove");
registerEventListener("Menu:Update");
registerEventListener("Gecko:Ready");
registerEventListener("Toast:Show");
registerEventListener("DOMFullScreen:Start");
registerEventListener("DOMFullScreen:Stop");
registerEventListener("ToggleChrome:Hide");
registerEventListener("ToggleChrome:Show");
registerEventListener("ToggleChrome:Focus");
registerEventListener("Permissions:Data");
registerEventListener("Tab:ViewportMetadata");
registerEventListener("Session:StatePurged");
registerEventListener("Bookmark:Insert");
registerEventListener("Accessibility:Event");
registerEventListener("Accessibility:Ready");
registerEventListener("Shortcut:Remove");
registerEventListener("WebApps:Open");
registerEventListener("WebApps:PreInstall");
registerEventListener("WebApps:PostInstall");
registerEventListener("WebApps:Install");
registerEventListener("WebApps:Uninstall");
registerEventListener("Share:Text");
registerEventListener("Share:Image");
registerEventListener("Wallpaper:Set");
registerEventListener("Sanitize:ClearHistory");
registerEventListener("Update:Check");
registerEventListener("Update:Download");
registerEventListener("Update:Install");
registerEventListener("PrivateBrowsing:Data");
registerEventListener("Contact:Add");
if (SmsManager.getInstance() != null) {
SmsManager.getInstance().start();
}
mPromptService = new PromptService(this);
mTextSelection = new TextSelection((TextSelectionHandle) findViewById(R.id.start_handle),
(TextSelectionHandle) findViewById(R.id.middle_handle),
(TextSelectionHandle) findViewById(R.id.end_handle),
GeckoAppShell.getEventDispatcher(),
this);
PrefsHelper.getPref("app.update.autodownload", new PrefsHelper.PrefHandlerBase() {
@Override public void prefValue(String pref, String value) {
UpdateServiceHelper.registerForUpdates(GeckoApp.this, value);
}
});
// Trigger the completion of the telemetry timer that wraps activity startup,
// then grab the duration to give to FHR.
mJavaUiStartupTimer.stop();
final long javaDuration = mJavaUiStartupTimer.getElapsed();
ThreadUtils.getBackgroundHandler().postDelayed(new Runnable() {
@Override
public void run() {
final BrowserHealthRecorder rec = mHealthRecorder;
if (rec != null) {
rec.recordJavaStartupTime(javaDuration);
}
// Sync settings need Gecko to be loaded, so
// no hurry in starting this.
checkMigrateSync();
// Record our launch time for the announcements service
// to use in assessing inactivity.
final Context context = GeckoApp.this;
AnnouncementsBroadcastService.recordLastLaunch(context);
// Kick off our background services that fetch product
// announcements and upload health reports. We do this by
// invoking the broadcast receiver, which uses the system alarm
// infrastructure to perform tasks at intervals.
GeckoPreferences.broadcastAnnouncementsPref(context);
GeckoPreferences.broadcastHealthReportUploadPref(context);
/*
XXXX see bug 635342
We want to disable this code if possible. It is about 145ms in runtime
SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);
String localeCode = settings.getString(getPackageName() + ".locale", "");
if (localeCode != null && localeCode.length() > 0)
GeckoAppShell.setSelectedLocale(localeCode);
*/
if (!GeckoThread.checkLaunchState(GeckoThread.LaunchState.Launched)) {
return;
}
}
}, 50);
if (mIsRestoringActivity) {
GeckoThread.setLaunchState(GeckoThread.LaunchState.GeckoRunning);
Tab selectedTab = Tabs.getInstance().getSelectedTab();
if (selectedTab != null)
Tabs.getInstance().notifyListeners(selectedTab, Tabs.TabEvents.SELECTED);
geckoConnected();
GeckoAppShell.setLayerClient(mLayerView.getLayerClient());
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Viewport:Flush", null));
}
if (ACTION_ALERT_CALLBACK.equals(action)) {
processAlertCallback(intent);
}
}
private String restoreSessionTabs(final boolean isExternalURL) throws SessionRestoreException {
try {
String sessionString = getProfile().readSessionFile(false);
if (sessionString == null) {
throw new SessionRestoreException("Could not read from session file");
}
// If we are doing an OOM restore, parse the session data and
// stub the restored tabs immediately. This allows the UI to be
// updated before Gecko has restored.
if (mRestoreMode == RESTORE_OOM) {
final JSONArray tabs = new JSONArray();
SessionParser parser = new SessionParser() {
@Override
public void onTabRead(SessionTab sessionTab) {
JSONObject tabObject = sessionTab.getTabObject();
int flags = Tabs.LOADURL_NEW_TAB;
flags |= ((isExternalURL || !sessionTab.isSelected()) ? Tabs.LOADURL_DELAY_LOAD : 0);
flags |= (tabObject.optBoolean("desktopMode") ? Tabs.LOADURL_DESKTOP : 0);
flags |= (tabObject.optBoolean("isPrivate") ? Tabs.LOADURL_PRIVATE : 0);
Tab tab = Tabs.getInstance().loadUrl(sessionTab.getUrl(), flags);
tab.updateTitle(sessionTab.getTitle());
try {
tabObject.put("tabId", tab.getId());
} catch (JSONException e) {
Log.e(LOGTAG, "JSON error", e);
}
tabs.put(tabObject);
}
};
if (mPrivateBrowsingSession == null) {
parser.parse(sessionString);
} else {
parser.parse(sessionString, mPrivateBrowsingSession);
}
if (tabs.length() > 0) {
sessionString = new JSONObject().put("windows", new JSONArray().put(new JSONObject().put("tabs", tabs))).toString();
} else {
throw new SessionRestoreException("No tabs could be read from session file");
}
}
JSONObject restoreData = new JSONObject();
restoreData.put("restoringOOM", mRestoreMode == RESTORE_OOM);
restoreData.put("sessionString", sessionString);
return restoreData.toString();
} catch (JSONException e) {
throw new SessionRestoreException(e);
}
}
public GeckoProfile getProfile() {
// fall back to default profile if we didn't load a specific one
if (mProfile == null) {
mProfile = GeckoProfile.get(this);
}
return mProfile;
}
protected int getSessionRestoreState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
return RESTORE_OOM;
}
final SharedPreferences prefs = GeckoApp.getAppSharedPreferences();
// We record crashes in the crash reporter. If sessionstore.js
// exists, but we didn't flag a crash in the crash reporter, we
// were probably just force killed by the user, so we shouldn't do
// a restore.
if (prefs.getBoolean(PREFS_CRASHED, false)) {
ThreadUtils.postToBackgroundThread(new Runnable() {
@Override
public void run() {
prefs.edit()
.putBoolean(GeckoApp.PREFS_CRASHED, false)
.commit();
}
});
if (getProfile().shouldRestoreSession()) {
return RESTORE_CRASH;
}
}
return RESTORE_NONE;
}
/**
* Enable Android StrictMode checks (for supported OS versions).
* http://developer.android.com/reference/android/os/StrictMode.html
*/
private void enableStrictMode() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
return;
}
Log.d(LOGTAG, "Enabling Android StrictMode");
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
}
public void enableCameraView() {
// Start listening for orientation events
mCameraOrientationEventListener = new OrientationEventListener(this) {
@Override
public void onOrientationChanged(int orientation) {
if (mAppStateListeners != null) {
for (GeckoAppShell.AppStateListener listener: mAppStateListeners) {
listener.onOrientationChanged();
}
}
}
};
mCameraOrientationEventListener.enable();
// Try to make it fully transparent.
if (mCameraView instanceof SurfaceView) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mCameraView.setAlpha(0.0f);
}
} else if (mCameraView instanceof TextureView) {
mCameraView.setAlpha(0.0f);
}
RelativeLayout mCameraLayout = (RelativeLayout) findViewById(R.id.camera_layout);
// Some phones (eg. nexus S) need at least a 8x16 preview size
mCameraLayout.addView(mCameraView,
new AbsoluteLayout.LayoutParams(8, 16, 0, 0));
}
public void disableCameraView() {
if (mCameraOrientationEventListener != null) {
mCameraOrientationEventListener.disable();
mCameraOrientationEventListener = null;
}
RelativeLayout mCameraLayout = (RelativeLayout) findViewById(R.id.camera_layout);
mCameraLayout.removeView(mCameraView);
}
public String getDefaultUAString() {
return HardwareUtils.isTablet() ? AppConstants.USER_AGENT_FENNEC_TABLET :
AppConstants.USER_AGENT_FENNEC_MOBILE;
}
public String getUAStringForHost(String host) {
// With our standard UA String, we get a 200 response code and
// client-side redirect from t.co. This bot-like UA gives us a
// 301 response code
if ("t.co".equals(host)) {
return AppConstants.USER_AGENT_BOT_LIKE;
}
return getDefaultUAString();
}
class PrefetchRunnable implements Runnable {
private String mPrefetchUrl;
PrefetchRunnable(String prefetchUrl) {
mPrefetchUrl = prefetchUrl;
}
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(mPrefetchUrl);
// data url should have an http scheme
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", getUAStringForHost(url.getHost()));
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.connect();
} catch (Exception e) {
Log.e(LOGTAG, "Exception prefetching URL", e);
} finally {
if (connection != null)
connection.disconnect();
}
}
}
private void processAlertCallback(Intent intent) {
String alertName = "";
String alertCookie = "";
Uri data = intent.getData();
if (data != null) {
alertName = data.getQueryParameter("name");
if (alertName == null)
alertName = "";
alertCookie = data.getQueryParameter("cookie");
if (alertCookie == null)
alertCookie = "";
}
handleNotification(ACTION_ALERT_CALLBACK, alertName, alertCookie);
if (intent.hasExtra(NotificationHelper.NOTIFICATION_ID)) {
String id = intent.getStringExtra(NotificationHelper.NOTIFICATION_ID);
mNotificationHelper.hideNotification(id);
}
}
@Override
protected void onNewIntent(Intent intent) {
if (GeckoThread.checkLaunchState(GeckoThread.LaunchState.GeckoExiting)) {
// We're exiting and shouldn't try to do anything else just incase
// we're hung for some reason we'll force the process to exit
System.exit(0);
return;
}
// if we were previously OOM killed, we can end up here when launching
// from external shortcuts, so set this as the intent for initialization
if (!mInitialized) {
setIntent(intent);
return;
}
// don't perform any actions if launching from recent apps
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0)
return;
final String action = intent.getAction();
if (Intent.ACTION_MAIN.equals(action)) {
GeckoAppShell.sendEventToGecko(GeckoEvent.createURILoadEvent(""));
} else if (ACTION_LOAD.equals(action)) {
String uri = intent.getDataString();
Tabs.getInstance().loadUrl(uri);
} else if (Intent.ACTION_VIEW.equals(action)) {
String uri = intent.getDataString();
GeckoAppShell.sendEventToGecko(GeckoEvent.createURILoadEvent(uri));
} else if (action != null && action.startsWith(ACTION_WEBAPP_PREFIX)) {
String uri = getURIFromIntent(intent);
GeckoAppShell.sendEventToGecko(GeckoEvent.createWebappLoadEvent(uri));
} else if (ACTION_BOOKMARK.equals(action)) {
String uri = getURIFromIntent(intent);
GeckoAppShell.sendEventToGecko(GeckoEvent.createBookmarkLoadEvent(uri));
} else if (Intent.ACTION_SEARCH.equals(action)) {
String uri = getURIFromIntent(intent);
GeckoAppShell.sendEventToGecko(GeckoEvent.createURILoadEvent(uri));
} else if (ACTION_ALERT_CALLBACK.equals(action)) {
processAlertCallback(intent);
} else if (ACTION_LAUNCH_SETTINGS.equals(action)) {
mIntentHandled = true;
// Check if launched from data reporting notification.
Intent settingsIntent = new Intent(GeckoApp.this, GeckoPreferences.class);
// Copy extras.
settingsIntent.putExtras(intent);
startActivity(settingsIntent);
}
}
/*
* Handles getting a uri from and intent in a way that is backwards
* compatable with our previous implementations
*/
protected String getURIFromIntent(Intent intent) {
final String action = intent.getAction();
if (ACTION_ALERT_CALLBACK.equals(action))
return null;
String uri = intent.getDataString();
if (uri != null)
return uri;
if ((action != null && action.startsWith(ACTION_WEBAPP_PREFIX)) || ACTION_BOOKMARK.equals(action)) {
uri = intent.getStringExtra("args");
if (uri != null && uri.startsWith("--url=")) {
uri.replace("--url=", "");
}
}
return uri;
}
@Override
public void onResume()
{
// After an onPause, the activity is back in the foreground.
// Undo whatever we did in onPause.
super.onResume();
int newOrientation = getResources().getConfiguration().orientation;
if (mOrientation != newOrientation) {
mOrientation = newOrientation;
refreshChrome();
}
GeckoScreenOrientationListener.getInstance().start();
// User may have enabled/disabled accessibility.
GeckoAccessibility.updateAccessibilitySettings(this);
if (mAppStateListeners != null) {
for (GeckoAppShell.AppStateListener listener: mAppStateListeners) {
listener.onResume();
}
}
// We use two times: a pseudo-unique wall-clock time to identify the
// current session across power cycles, and the elapsed realtime to
// track the duration of the session.
final long now = System.currentTimeMillis();
final long realTime = android.os.SystemClock.elapsedRealtime();
ThreadUtils.postToBackgroundThread(new Runnable() {
@Override
public void run() {
// Now construct the new session on BrowserHealthRecorder's behalf. We do this here
// so it can benefit from a single near-startup prefs commit.
SessionInformation currentSession = new SessionInformation(now, realTime);
SharedPreferences prefs = GeckoApp.getAppSharedPreferences();
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(GeckoApp.PREFS_WAS_STOPPED, false);
currentSession.recordBegin(editor);
editor.commit();
final BrowserHealthRecorder rec = mHealthRecorder;
if (rec != null) {
rec.setCurrentSession(currentSession);
} else {
Log.w(LOGTAG, "Can't record session: rec is null.");
}
}
});
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!mInitialized && hasFocus) {
initialize();
getWindow().setBackgroundDrawable(null);
}
}
@Override
public void onPause()
{
final BrowserHealthRecorder rec = mHealthRecorder;
// In some way it's sad that Android will trigger StrictMode warnings
// here as the whole point is to save to disk while the activity is not
// interacting with the user.
ThreadUtils.postToBackgroundThread(new Runnable() {
@Override
public void run() {
SharedPreferences prefs = GeckoApp.getAppSharedPreferences();
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(GeckoApp.PREFS_WAS_STOPPED, true);
if (rec != null) {
rec.recordSessionEnd("P", editor);
}
editor.commit();
}
});
GeckoScreenOrientationListener.getInstance().stop();
if (mAppStateListeners != null) {
for(GeckoAppShell.AppStateListener listener: mAppStateListeners) {
listener.onPause();
}
}
super.onPause();
}
@Override
public void onRestart()
{
ThreadUtils.postToBackgroundThread(new Runnable() {
@Override
public void run() {
SharedPreferences prefs = GeckoApp.getAppSharedPreferences();
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(GeckoApp.PREFS_WAS_STOPPED, false);
editor.commit();
}
});
super.onRestart();
}
@Override
public void onDestroy()
{
unregisterEventListener("log");
unregisterEventListener("Reader:ListCountRequest");
unregisterEventListener("Reader:Added");
unregisterEventListener("Reader:Removed");
unregisterEventListener("Reader:Share");
unregisterEventListener("Reader:FaviconRequest");
unregisterEventListener("Reader:GoToReadingList");
unregisterEventListener("onCameraCapture");
unregisterEventListener("Menu:Add");
unregisterEventListener("Menu:Remove");
unregisterEventListener("Menu:Update");
unregisterEventListener("Gecko:Ready");
unregisterEventListener("Toast:Show");
unregisterEventListener("DOMFullScreen:Start");
unregisterEventListener("DOMFullScreen:Stop");
unregisterEventListener("ToggleChrome:Hide");
unregisterEventListener("ToggleChrome:Show");
unregisterEventListener("ToggleChrome:Focus");
unregisterEventListener("Permissions:Data");
unregisterEventListener("Tab:ViewportMetadata");
unregisterEventListener("Session:StatePurged");
unregisterEventListener("Bookmark:Insert");
unregisterEventListener("Accessibility:Event");
unregisterEventListener("Accessibility:Ready");
unregisterEventListener("Shortcut:Remove");
unregisterEventListener("WebApps:Open");
unregisterEventListener("WebApps:PreInstall");
unregisterEventListener("WebApps:PostInstall");
unregisterEventListener("WebApps:Install");
unregisterEventListener("WebApps:Uninstall");
unregisterEventListener("Share:Text");
unregisterEventListener("Share:Image");
unregisterEventListener("Wallpaper:Set");
unregisterEventListener("Sanitize:ClearHistory");
unregisterEventListener("Update:Check");
unregisterEventListener("Update:Download");
unregisterEventListener("Update:Install");
unregisterEventListener("PrivateBrowsing:Data");
unregisterEventListener("Contact:Add");
deleteTempFiles();
if (mLayerView != null)
mLayerView.destroy();
if (mDoorHangerPopup != null)
mDoorHangerPopup.destroy();
if (mFormAssistPopup != null)
mFormAssistPopup.destroy();
if (mPromptService != null)
mPromptService.destroy();
if (mTextSelection != null)
mTextSelection.destroy();
if (mNotificationHelper != null)
mNotificationHelper.destroy();
Tabs.getInstance().detachFromActivity(this);
if (SmsManager.getInstance() != null) {
SmsManager.getInstance().stop();
if (isFinishing())
SmsManager.getInstance().shutdown();
}
final BrowserHealthRecorder rec = mHealthRecorder;
mHealthRecorder = null;
if (rec != null) {
// Closing a BrowserHealthRecorder could incur a write.
ThreadUtils.postToBackgroundThread(new Runnable() {
@Override
public void run() {
rec.close();
}
});
}
super.onDestroy();
Tabs.unregisterOnTabsChangedListener(this);
}
protected void registerEventListener(String event) {
GeckoAppShell.getEventDispatcher().registerEventListener(event, this);
}
protected void unregisterEventListener(String event) {
GeckoAppShell.getEventDispatcher().unregisterEventListener(event, this);
}
// Get a temporary directory, may return null
public static File getTempDirectory() {
File dir = sAppContext.getExternalFilesDir("temp");
return dir;
}
// Delete any files in our temporary directory
public static void deleteTempFiles() {
File dir = getTempDirectory();
if (dir == null)
return;
File[] files = dir.listFiles();
if (files == null)
return;
for (File file : files) {
file.delete();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (mOrientation != newConfig.orientation) {
mOrientation = newConfig.orientation;
if (mFormAssistPopup != null)
mFormAssistPopup.hide();
refreshChrome();
}
}
public String getContentProcessName() {
return AppConstants.MOZ_CHILD_PROCESS_NAME;
}
/*
* Only one factory can be set on the inflater; however, we want to use two
* factories (GeckoViewsFactory and the FragmentActivity factory).
* Overriding onCreateView() here allows us to dispatch view creation to
* both factories.
*/
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
View view = GeckoViewsFactory.getInstance().onCreateView(name, context, attrs);
if (view == null) {
view = super.onCreateView(name, context, attrs);
}
return view;
}
public void addEnvToIntent(Intent intent) {
Map<String,String> envMap = System.getenv();
Set<Map.Entry<String,String>> envSet = envMap.entrySet();
Iterator<Map.Entry<String,String>> envIter = envSet.iterator();
int c = 0;
while (envIter.hasNext()) {
Map.Entry<String,String> entry = envIter.next();
intent.putExtra("env" + c, entry.getKey() + "="
+ entry.getValue());
c++;
}
}
public void doRestart() {
doRestart(RESTARTER_ACTION);
}
public void doRestart(String action) {
Log.d(LOGTAG, "doRestart(\"" + action + "\")");
try {
Intent intent = new Intent(action);
intent.setClassName(AppConstants.ANDROID_PACKAGE_NAME, RESTARTER_CLASS);
/* TODO: addEnvToIntent(intent); */
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
Log.d(LOGTAG, "Restart intent: " + intent.toString());
GeckoAppShell.killAnyZombies();
startActivity(intent);
} catch (Exception e) {
Log.e(LOGTAG, "Error effecting restart.", e);
}
finish();
// Give the restart process time to start before we die
GeckoAppShell.waitForAnotherGeckoProc();
}
public void handleNotification(String action, String alertName, String alertCookie) {
// If Gecko isn't running yet, we ignore the notification. Note that
// even if Gecko is running but it was restarted since the notification
// was created, the notification won't be handled (bug 849653).
if (GeckoThread.checkLaunchState(GeckoThread.LaunchState.GeckoRunning)) {
GeckoAppShell.handleNotification(action, alertName, alertCookie);
}
}
private void checkMigrateProfile() {
final File profileDir = getProfile().getDir();
if (profileDir != null) {
final GeckoApp app = GeckoApp.sAppContext;
ThreadUtils.postToBackgroundThread(new Runnable() {
@Override
public void run() {
ProfileMigrator profileMigrator = new ProfileMigrator(app);
// Do a migration run on the first start after an upgrade.
if (!GeckoApp.sIsUsingCustomProfile &&
!profileMigrator.hasMigrationRun()) {
// Show the "Setting up Fennec" screen if this takes
// a while.
// Create a "final" holder for the setup screen so that we can
// create it in startCallback and still find a reference to it
// in stopCallback. (We must create it on the UI thread to fix
// bug 788216). Note that synchronization is not a problem here
// since it is only ever touched on the UI thread.
final SetupScreen[] setupScreenHolder = new SetupScreen[1];
final Runnable startCallback = new Runnable() {
@Override
public void run() {
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
setupScreenHolder[0] = new SetupScreen(app);
setupScreenHolder[0].show();
}
});
}
};
final Runnable stopCallback = new Runnable() {
@Override
public void run() {
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
SetupScreen screen = setupScreenHolder[0];
// screen will never be null if this code runs, but
// stranger things have happened...
if (screen != null) {
screen.dismiss();
}
}
});
}
};
profileMigrator.setLongOperationCallbacks(startCallback,
stopCallback);
profileMigrator.launchPlaces(profileDir);
finishProfileMigration();
}
}}
);
}
}
protected void finishProfileMigration() {
}
private void checkMigrateSync() {
final File profileDir = getProfile().getDir();
if (!GeckoApp.sIsUsingCustomProfile && profileDir != null) {
final GeckoApp app = GeckoApp.sAppContext;
ProfileMigrator profileMigrator = new ProfileMigrator(app);
if (!profileMigrator.hasSyncMigrated()) {
profileMigrator.launchSyncPrefs();
}
}
}
public PromptService getPromptService() {
return mPromptService;
}
public void showReadingList() {
Intent intent = new Intent(getBaseContext(), AwesomeBar.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.putExtra(AwesomeBar.TARGET_KEY, AwesomeBar.Target.CURRENT_TAB.toString());
intent.putExtra(AwesomeBar.READING_LIST_KEY, true);
int requestCode = GeckoAppShell.sActivityHelper.makeRequestCodeForAwesomebar();
startActivityForResult(intent, requestCode);
}
@Override
public void onBackPressed() {
if (autoHideTabs()) {
return;
}
if (mDoorHangerPopup != null && mDoorHangerPopup.isShowing()) {
mDoorHangerPopup.dismiss();
return;
}
if (mFullScreenPluginView != null) {
GeckoAppShell.onFullScreenPluginHidden(mFullScreenPluginView);
removeFullScreenPluginView(mFullScreenPluginView);
return;
}
if (mLayerView != null && mLayerView.isFullScreen()) {
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("FullScreen:Exit", null));
return;
}
Tabs tabs = Tabs.getInstance();
Tab tab = tabs.getSelectedTab();
if (tab == null) {
moveTaskToBack(true);
return;
}
if (tab.doBack())
return;
if (tab.isExternal()) {
moveTaskToBack(true);
tabs.closeTab(tab);
return;
}
int parentId = tab.getParentId();
Tab parent = tabs.getTab(parentId);
if (parent != null) {
// The back button should always return to the parent (not a sibling).
tabs.closeTab(tab, parent);
return;
}
moveTaskToBack(true);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!GeckoAppShell.sActivityHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
public AbsoluteLayout getPluginContainer() { return mPluginContainer; }
// Accelerometer.
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
GeckoAppShell.sendEventToGecko(GeckoEvent.createSensorEvent(event));
}
// Geolocation.
@Override
public void onLocationChanged(Location location) {
// No logging here: user-identifying information.
GeckoAppShell.sendEventToGecko(GeckoEvent.createLocationEvent(location));
}
@Override
public void onProviderDisabled(String provider)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
// Called when a Gecko Hal WakeLock is changed
public void notifyWakeLockChanged(String topic, String state) {
PowerManager.WakeLock wl = mWakeLocks.get(topic);
if (state.equals("locked-foreground") && wl == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, topic);
wl.acquire();
mWakeLocks.put(topic, wl);
} else if (!state.equals("locked-foreground") && wl != null) {
wl.release();
mWakeLocks.remove(topic);
}
}
public void notifyCheckUpdateResult(String result) {
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Update:CheckResult", result));
}
protected void geckoConnected() {
mLayerView.geckoConnected();
}
public void setAccessibilityEnabled(boolean enabled) {
}
public static class MainLayout extends RelativeLayout {
private TouchEventInterceptor mTouchEventInterceptor;
private MotionEventInterceptor mMotionEventInterceptor;
public MainLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setTouchEventInterceptor(TouchEventInterceptor interceptor) {
mTouchEventInterceptor = interceptor;
}
public void setMotionEventInterceptor(MotionEventInterceptor interceptor) {
mMotionEventInterceptor = interceptor;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (mTouchEventInterceptor != null && mTouchEventInterceptor.onInterceptTouchEvent(this, event)) {
return true;
}
return super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mTouchEventInterceptor != null && mTouchEventInterceptor.onTouch(this, event)) {
return true;
}
return super.onTouchEvent(event);
}
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (mMotionEventInterceptor != null && mMotionEventInterceptor.onInterceptMotionEvent(this, event)) {
return true;
}
return super.onGenericMotionEvent(event);
}
@Override
public void setDrawingCacheEnabled(boolean enabled) {
// Instead of setting drawing cache in the view itself, we simply
// enable drawing caching on its children. This is mainly used in
// animations (see PropertyAnimator)
super.setChildrenDrawnWithCacheEnabled(enabled);
}
}
private class FullScreenHolder extends FrameLayout {
public FullScreenHolder(Context ctx) {
super(ctx);
}
@Override
public void addView(View view, int index) {
/**
* This normally gets called when Flash adds a separate SurfaceView
* for the video. It is unhappy if we have the LayerView underneath
* it for some reason so we need to hide that. Hiding the LayerView causes
* its surface to be destroyed, which causes a pause composition
* event to be sent to Gecko. We synchronously wait for that to be
* processed. Simultaneously, however, Flash is waiting on a mutex so
* the post() below is an attempt to avoid a deadlock.
*/
super.addView(view, index);
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
mLayerView.hide();
}
});
}
/**
* The methods below are simply copied from what Android WebKit does.
* It wasn't ever called in my testing, but might as well
* keep it in case it is for some reason. The methods
* all return true because we don't want any events
* leaking out from the fullscreen view.
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.isSystem()) {
return super.onKeyDown(keyCode, event);
}
mFullScreenPluginView.onKeyDown(keyCode, event);
return true;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (event.isSystem()) {
return super.onKeyUp(keyCode, event);
}
mFullScreenPluginView.onKeyUp(keyCode, event);
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
mFullScreenPluginView.onTrackballEvent(event);
return true;
}
}
protected NotificationClient makeNotificationClient() {
// Don't use a notification service; we may be killed in the background
// during downloads.
return new AppNotificationClient(getApplicationContext());
}
}
|