summaryrefslogtreecommitdiffstats
path: root/chrome/browser/ui/search/instant_extended_interactive_uitest.cc
blob: e0354bbc5d4e6e439c46d284ea1e182ac49cb1dc (plain)
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
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <sstream>

#include "base/command_line.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_base.h"
#include "base/metrics/histogram_samples.h"
#include "base/metrics/statistics_recorder.h"
#include "base/prefs/pref_service.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/strings/string_number_conversions.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete_controller.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_provider.h"
#include "chrome/browser/autocomplete/autocomplete_result.h"
#include "chrome/browser/autocomplete/search_provider.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/history/history_db_task.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/history/history_types.h"
#include "chrome/browser/history/top_sites.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search/instant_service.h"
#include "chrome/browser/search/instant_service_factory.h"
#include "chrome/browser/search/search.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/task_manager/task_manager_browsertest_util.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/omnibox/omnibox_view.h"
#include "chrome/browser/ui/search/instant_commit_type.h"
#include "chrome/browser/ui/search/instant_ntp.h"
#include "chrome/browser/ui/search/instant_overlay.h"
#include "chrome/browser/ui/search/instant_tab.h"
#include "chrome/browser/ui/search/instant_test_utils.h"
#include "chrome/browser/ui/search/search_tab_helper.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/webui/theme_source.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/instant_types.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/thumbnail_score.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/sessions/serialized_navigation_entry.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "content/public/common/bindings_policy.h"
#include "content/public/common/renderer_preferences.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "grit/generated_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/l10n/l10n_util.h"

#if defined(HTML_INSTANT_EXTENDED_POPUP)

namespace {

// Creates a bitmap of the specified color. Caller takes ownership.
gfx::Image CreateBitmap(SkColor color) {
  SkBitmap thumbnail;
  thumbnail.setConfig(SkBitmap::kARGB_8888_Config, 4, 4);
  thumbnail.allocPixels();
  thumbnail.eraseColor(color);
  return gfx::Image::CreateFrom1xBitmap(thumbnail);  // adds ref.
}

// Task used to make sure history has finished processing a request. Intended
// for use with BlockUntilHistoryProcessesPendingRequests.
class QuittingHistoryDBTask : public history::HistoryDBTask {
 public:
  QuittingHistoryDBTask() {}

  virtual bool RunOnDBThread(history::HistoryBackend* backend,
                             history::HistoryDatabase* db) OVERRIDE {
    return true;
  }

  virtual void DoneRunOnMainThread() OVERRIDE {
    base::MessageLoop::current()->Quit();
  }

 private:
  virtual ~QuittingHistoryDBTask() {}

  DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask);
};

}  // namespace

class InstantExtendedTest : public InProcessBrowserTest,
                            public InstantTestBase {
 public:
  InstantExtendedTest()
      : on_most_visited_change_calls_(0),
        most_visited_items_count_(0),
        first_most_visited_item_id_(0),
        on_native_suggestions_calls_(0),
        on_change_calls_(0),
        submit_count_(0),
        on_esc_key_press_event_calls_(0),
        on_focus_changed_calls_(0),
        is_focused_(false),
        on_toggle_voice_search_calls_(0) {
  }
 protected:
  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    chrome::EnableInstantExtendedAPIForTesting();
    ASSERT_TRUE(https_test_server().Start());
    GURL instant_url = https_test_server().GetURL(
        "files/instant_extended.html?strk=1&");
    InstantTestBase::Init(instant_url);
  }

  virtual void SetUpOnMainThread() OVERRIDE {
    browser()->toolbar_model()->SetSupportsExtractionOfURLLikeSearchTerms(true);
  }

  int64 GetHistogramCount(const char* name) {
    base::HistogramBase* histogram =
        base::StatisticsRecorder::FindHistogram(name);
    if (!histogram) {
      // If no histogram is found, it's possible that no values have been
      // recorded yet. Assume that the value is zero.
      return 0;
    }
    return histogram->SnapshotSamples()->TotalCount();
  }

  std::string GetOmniboxText() {
    return UTF16ToUTF8(omnibox()->GetText());
  }

  void SendDownArrow() {
    omnibox()->model()->OnUpOrDownKeyPressed(1);
    // Wait for JavaScript to run the key handler by executing a blank script.
    EXPECT_TRUE(ExecuteScript(std::string()));
  }

  void SendUpArrow() {
    omnibox()->model()->OnUpOrDownKeyPressed(-1);
    // Wait for JavaScript to run the key handler by executing a blank script.
    EXPECT_TRUE(ExecuteScript(std::string()));
  }

  void SendEscape() {
    omnibox()->model()->OnEscapeKeyPressed();
    // Wait for JavaScript to run the key handler by executing a blank script.
    EXPECT_TRUE(ExecuteScript(std::string()));
  }

  bool UpdateSearchState(content::WebContents* contents) WARN_UNUSED_RESULT {
    return GetIntFromJS(contents, "onMostVisitedChangedCalls",
                        &on_most_visited_change_calls_) &&
           GetIntFromJS(contents, "mostVisitedItemsCount",
                        &most_visited_items_count_) &&
           GetIntFromJS(contents, "firstMostVisitedItemId",
                        &first_most_visited_item_id_) &&
           GetIntFromJS(contents, "onNativeSuggestionsCalls",
                        &on_native_suggestions_calls_) &&
           GetIntFromJS(contents, "onChangeCalls",
                        &on_change_calls_) &&
           GetIntFromJS(contents, "submitCount",
                        &submit_count_) &&
           GetStringFromJS(contents, "apiHandle.value",
                           &query_value_) &&
           GetIntFromJS(contents, "onEscKeyPressedCalls",
                        &on_esc_key_press_event_calls_) &&
           GetIntFromJS(contents, "onFocusChangedCalls",
                       &on_focus_changed_calls_) &&
           GetBoolFromJS(contents, "isFocused",
                         &is_focused_) &&
           GetIntFromJS(contents, "onToggleVoiceSearchCalls",
                        &on_toggle_voice_search_calls_);
  }

  TemplateURL* GetDefaultSearchProviderTemplateURL() {
    TemplateURLService* template_url_service =
        TemplateURLServiceFactory::GetForProfile(browser()->profile());
    if (template_url_service)
      return template_url_service->GetDefaultSearchProvider();
    return NULL;
  }

  bool AddSearchToHistory(string16 term, int visit_count) {
    TemplateURL* template_url = GetDefaultSearchProviderTemplateURL();
    if (!template_url)
      return false;

    HistoryService* history = HistoryServiceFactory::GetForProfile(
        browser()->profile(), Profile::EXPLICIT_ACCESS);
    GURL search(template_url->url_ref().ReplaceSearchTerms(
        TemplateURLRef::SearchTermsArgs(term)));
    history->AddPageWithDetails(
        search, string16(), visit_count, visit_count,
        base::Time::Now(), false, history::SOURCE_BROWSED);
    history->SetKeywordSearchTermsForURL(
        search, template_url->id(), term);
    return true;
  }

  void BlockUntilHistoryProcessesPendingRequests() {
    HistoryService* history = HistoryServiceFactory::GetForProfile(
        browser()->profile(), Profile::EXPLICIT_ACCESS);
    DCHECK(history);
    DCHECK(base::MessageLoop::current());

    CancelableRequestConsumer consumer;
    history->ScheduleDBTask(new QuittingHistoryDBTask(), &consumer);
    base::MessageLoop::current()->Run();
  }

  int CountSearchProviderSuggestions() {
    return omnibox()->model()->autocomplete_controller()->search_provider()->
        matches().size();
  }

  int on_most_visited_change_calls_;
  int most_visited_items_count_;
  int first_most_visited_item_id_;
  int on_native_suggestions_calls_;
  int on_change_calls_;
  int submit_count_;
  int on_esc_key_press_event_calls_;
  std::string query_value_;
  int on_focus_changed_calls_;
  bool is_focused_;
  int on_toggle_voice_search_calls_;
};

// Test class used to verify chrome-search: scheme and access policy from the
// Instant overlay.  This is a subclass of |ExtensionBrowserTest| because it
// loads a theme that provides a background image.
class InstantPolicyTest : public ExtensionBrowserTest, public InstantTestBase {
 public:
  InstantPolicyTest() {}

 protected:
  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    chrome::EnableInstantExtendedAPIForTesting();
    ASSERT_TRUE(https_test_server().Start());
    GURL instant_url = https_test_server().GetURL(
        "files/instant_extended.html?strk=1&");
    InstantTestBase::Init(instant_url);
  }

  void InstallThemeSource() {
    ThemeSource* theme = new ThemeSource(profile());
    content::URLDataSource::Add(profile(), theme);
  }

  void InstallThemeAndVerify(const std::string& theme_dir,
                             const std::string& theme_name) {
    const base::FilePath theme_path = test_data_dir_.AppendASCII(theme_dir);
    ASSERT_TRUE(InstallExtensionWithUIAutoConfirm(
        theme_path, 1, ExtensionBrowserTest::browser()));
    const extensions::Extension* theme =
        ThemeServiceFactory::GetThemeForProfile(
            ExtensionBrowserTest::browser()->profile());
    ASSERT_NE(static_cast<extensions::Extension*>(NULL), theme);
    ASSERT_EQ(theme->name(), theme_name);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(InstantPolicyTest);
};

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, ExtendedModeIsOn) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  EXPECT_TRUE(instant()->extended_enabled_);
}

// Test that Instant is preloaded when the omnibox is focused.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OmniboxFocusLoadsInstant) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));

  // Explicitly unfocus the omnibox.
  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);

  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER));
  EXPECT_FALSE(omnibox()->model()->has_focus());

  // Delete any existing overlay.
  instant()->overlay_.reset();
  EXPECT_FALSE(instant()->GetOverlayContents());

  // Refocus the omnibox. The InstantController should've preloaded Instant.
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  EXPECT_FALSE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER));
  EXPECT_TRUE(omnibox()->model()->has_focus());

  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(overlay);

  // Check that the page supports Instant, but it isn't showing.
  EXPECT_TRUE(instant()->overlay_->supports_instant());
  EXPECT_FALSE(instant()->IsOverlayingSearchResults());
  EXPECT_TRUE(instant()->model()->mode().is_default());

  // Adding a new tab shouldn't delete or recreate the overlay; otherwise,
  // what's the point of preloading?
  AddBlankTabAndShow(browser());
  EXPECT_EQ(overlay, instant()->GetOverlayContents());

  // Unfocusing and refocusing the omnibox should also preserve the overlay.
  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER));

  FocusOmnibox();
  EXPECT_FALSE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER));
  EXPECT_EQ(overlay, instant()->GetOverlayContents());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, InputShowsOverlay) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));

  // Focus omnibox and confirm overlay isn't shown.
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(overlay);
  EXPECT_FALSE(instant()->IsOverlayingSearchResults());
  EXPECT_TRUE(instant()->model()->mode().is_default());

  // Typing in the omnibox should show the overlay.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
  EXPECT_TRUE(instant()->model()->mode().is_search_suggestions());
  EXPECT_EQ(overlay, instant()->GetOverlayContents());
}

// Flaky on Linux Tests bot.
#if defined(OS_LINUX)
#define MAYBE_UsesOverlayIfTabNotReady DISABLED_UsesOverlayIfTabNotReady
#else
#define MAYBE_UsesOverlayIfTabNotReady UsesOverlayIfTabNotReady
#endif

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, MAYBE_UsesOverlayIfTabNotReady) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Open a new tab and start typing before InstantTab is properly hooked up.
  // Should use the overlay.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));

  // But Instant tab should still exist.
  ASSERT_NE(static_cast<InstantTab*>(NULL), instant()->instant_tab());
  EXPECT_FALSE(instant()->UseTabForSuggestions());

  // Wait for Instant Tab support if it still hasn't finished loading.
  if (!instant()->instant_tab()->supports_instant()) {
    content::WindowedNotificationObserver instant_tab_observer(
        chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
        content::NotificationService::AllSources());
    instant_tab_observer.Wait();
  }

  // Hide the overlay. Now, we should be using Instant tab for suggestions.
  instant()->HideOverlay();
  EXPECT_TRUE(instant()->UseTabForSuggestions());
}

// Flaky on Mac Tests bot. crbug.com/242415
#if defined(OS_MACOSX)
#define MAYBE_MiddleClickOnSuggestionOpensInNewTab DISABLED_MiddleClickOnSuggestionOpensInNewTab
#else
#define MAYBE_MiddleClickOnSuggestionOpensInNewTab MiddleClickOnSuggestionOpensInNewTab
#endif

// Test that middle clicking on a suggestion opens the result in a new tab.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       MAYBE_MiddleClickOnSuggestionOpensInNewTab) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  EXPECT_EQ(1, browser()->tab_strip_model()->count());

  // Typing in the omnibox should show the overlay.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("http://www.example.com/"));

  // Create an event listener that opens the top suggestion in a new tab.
  EXPECT_TRUE(ExecuteScript(
      "var rid = getApiHandle().nativeSuggestions[0].rid;"
      "document.body.addEventListener('click', function() {"
        "chrome.embeddedSearch.navigateContentWindow(rid, 2);"
      "});"
      ));

  content::WindowedNotificationObserver observer(
        chrome::NOTIFICATION_TAB_ADDED,
        content::NotificationService::AllSources());

  // Click to trigger the event listener.
  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);

  // Wait for the new tab to be added.
  observer.Wait();

  // Check that the new tab URL is as expected.
  content::WebContents* new_tab_contents =
      browser()->tab_strip_model()->GetWebContentsAt(1);
  EXPECT_EQ("http://www.example.com/", new_tab_contents->GetURL().spec());

  // Check that there are now two tabs.
  EXPECT_EQ(2, browser()->tab_strip_model()->count());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       UnfocusingOmniboxDoesNotChangeSuggestions) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  // Get a committed tab to work with.
  content::WebContents* instant_tab = instant()->GetOverlayContents();
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("committed"));
  browser()->window()->GetLocationBar()->AcceptInput();

  // Put focus back into the omnibox, type, and wait for some gray text.
  EXPECT_TRUE(content::ExecuteScript(instant_tab,
                                     "suggestion = 'santa claus';"));
  SetOmniboxTextAndWaitForSuggestion("santa ");
  EXPECT_EQ(ASCIIToUTF16("claus"), GetGrayText());
  EXPECT_TRUE(content::ExecuteScript(instant_tab,
      "onChangeCalls = onNativeSuggestionsCalls = 0;"));

  // Now unfocus the omnibox.
  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
  EXPECT_TRUE(UpdateSearchState(instant_tab));
  EXPECT_EQ(0, on_change_calls_);
  EXPECT_EQ(0, on_native_suggestions_calls_);
}

// Test that omnibox text is correctly set when overlay is committed with Enter.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OmniboxTextUponEnterCommit) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // The page will autocomplete once we set the omnibox value.
  EXPECT_TRUE(ExecuteScript("suggestion = 'santa claus';"));

  // Set the text, and wait for suggestions to show up.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("santa"));
  EXPECT_EQ(ASCIIToUTF16("santa"), omnibox()->GetText());

  // Test that the current suggestion is correctly set.
  EXPECT_EQ(ASCIIToUTF16(" claus"), GetGrayText());

  // Commit the search by pressing Enter.
  browser()->window()->GetLocationBar()->AcceptInput();

  // 'Enter' commits the query as it was typed.
  EXPECT_EQ(ASCIIToUTF16("santa"), omnibox()->GetText());

  // Suggestion should be cleared at this point.
  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());
}

// Test that omnibox text is correctly set when committed with focus lost.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OmniboxTextUponFocusLostCommit) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Set autocomplete text (grey text).
  EXPECT_TRUE(ExecuteScript("suggestion = 'johnny depp';"));

  // Set the text, and wait for suggestions to show up.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("johnny"));
  EXPECT_EQ(ASCIIToUTF16("johnny"), omnibox()->GetText());

  // Test that the current suggestion is correctly set.
  EXPECT_EQ(ASCIIToUTF16(" depp"), GetGrayText());

  // Commit the overlay by lost focus (e.g. clicking on the page).
  instant()->CommitIfPossible(INSTANT_COMMIT_FOCUS_LOST);

  // Omnibox text and suggestion should not be changed.
  EXPECT_EQ(ASCIIToUTF16("johnny"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16(" depp"), GetGrayText());
}

// Test that omnibox text is correctly set when clicking on committed SERP.
// Disabled on Mac because omnibox focus loss is not working correctly.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       OmniboxTextUponFocusedCommittedSERP) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Create an observer to wait for the instant tab to support Instant.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
      content::NotificationService::AllSources());

  // Do a search and commit it.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("hello k"));
  EXPECT_EQ(ASCIIToUTF16("hello k"), omnibox()->GetText());
  browser()->window()->GetLocationBar()->AcceptInput();
  observer.Wait();

  // With a committed results page, do a search by unfocusing the omnibox and
  // focusing the contents.
  SetOmniboxText("hello");
  // Calling handleOnChange manually to make sure it is called before the
  // Focus() call below.
  EXPECT_TRUE(content::ExecuteScript(instant()->instant_tab()->contents(),
                                     "suggestion = 'hello kitty';"
                                     "handleOnChange();"));
  instant()->instant_tab()->contents()->GetView()->Focus();

  // Omnibox text and suggestion should not be changed.
  EXPECT_EQ(ASCIIToUTF16("hello"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16(" kitty"), GetGrayText());
}

// Checks that a previous Navigation suggestion is not re-used when a search
// suggestion comes in.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       NavigationSuggestionIsDiscardedUponSearchSuggestion) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Tell the page to send a URL suggestion.
  EXPECT_TRUE(ExecuteScript("suggestion = 'http://www.example.com';"
                            "behavior = 1;"));
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("exa"));
  EXPECT_EQ(ASCIIToUTF16("example.com"), omnibox()->GetText());

  // Now send a search suggestion and see that Navigation suggestion is no
  // longer kept.
  EXPECT_TRUE(ExecuteScript("suggestion = 'exams are great';"
                            "behavior = 2;"));
  SetOmniboxText("exam");
  // Wait for JavaScript to run handleOnChange by executing a blank script.
  EXPECT_TRUE(ExecuteScript(std::string()));

  instant()->overlay()->contents()->GetView()->Focus();
  EXPECT_EQ(ASCIIToUTF16("exam"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16("s are great"), GetGrayText());

  // TODO(jered): Remove this after fixing OnBlur().
  omnibox()->RevertAll();
}

// This test simulates a search provider using the InstantExtended API to
// navigate through the suggested results and back to the original user query.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NavigateSuggestionsWithArrowKeys) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("hello"));
  EXPECT_EQ("hello", GetOmniboxText());

  SendDownArrow();
  EXPECT_EQ("result 1", GetOmniboxText());
  SendDownArrow();
  EXPECT_EQ("result 2", GetOmniboxText());
  SendUpArrow();
  EXPECT_EQ("result 1", GetOmniboxText());
  SendUpArrow();
  EXPECT_EQ("hello", GetOmniboxText());

  // Ensure that the API's value is set correctly.
  std::string result;
  EXPECT_TRUE(GetStringFromJS(instant()->GetOverlayContents(),
                              "window.chrome.searchBox.value",
                              &result));
  EXPECT_EQ("hello", result);

  EXPECT_TRUE(HasUserInputInProgress());
  // TODO(beaudoin): Figure out why this fails.
  // EXPECT_FALSE(HasTemporaryText());

  // Commit the search by pressing Enter.
  browser()->window()->GetLocationBar()->AcceptInput();
  EXPECT_EQ("hello", GetOmniboxText());
}

// Flaky on Linux Tests bot.  See http://crbug.com/233090.
#if defined(OS_LINUX)
#define MAYBE_NavigateToURLSuggestionHitEnterAndLookForSubmit DISABLED_NavigateToURLSuggestionHitEnterAndLookForSubmit
#else
#define MAYBE_NavigateToURLSuggestionHitEnterAndLookForSubmit NavigateToURLSuggestionHitEnterAndLookForSubmit
#endif

// This test simulates a search provider using the InstantExtended API to
// navigate through the suggested results and back to the original user query.
// If this test starts to flake, it may be that the second call to AcceptInput
// below causes instant()->instant_tab() to no longer be valid due to e.g. a
// navigation. In that case, see https://codereview.chromium.org/12895007/#msg28
// and onwards for possible alternatives.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       MAYBE_NavigateToURLSuggestionHitEnterAndLookForSubmit) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Create an observer to wait for the instant tab to support Instant.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
      content::NotificationService::AllSources());

  // Do a search and commit it.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("hello k"));
  EXPECT_EQ(ASCIIToUTF16("hello k"), omnibox()->GetText());
  browser()->window()->GetLocationBar()->AcceptInput();
  observer.Wait();

  SetOmniboxText("http");
  EXPECT_EQ("http", GetOmniboxText());

  SendDownArrow();
  EXPECT_EQ("result 1", GetOmniboxText());
  SendDownArrow();
  EXPECT_EQ("result 2", GetOmniboxText());

  // Set the next suggestion to be of type INSTANT_SUGGESTION_URL.
  EXPECT_TRUE(content::ExecuteScript(instant()->instant_tab()->contents(),
                                     "suggestionType = 1;"));
  SendDownArrow();
  EXPECT_EQ("http://www.google.com", GetOmniboxText());

  EXPECT_TRUE(HasUserInputInProgress());

  EXPECT_TRUE(UpdateSearchState(instant()->instant_tab()->contents()));
  // Note the commit count is initially 1 due to the AcceptInput() call above.
  EXPECT_EQ(1, submit_count_);

  std::string old_query_value(query_value_);

  // Commit the search by pressing Enter.
  browser()->window()->GetLocationBar()->AcceptInput();

  // Make sure a submit message got sent.
  EXPECT_TRUE(UpdateSearchState(instant()->instant_tab()->contents()));
  EXPECT_EQ(2, submit_count_);
  EXPECT_EQ(old_query_value, query_value_);
}

// This test simulates a search provider using the InstantExtended API to
// navigate through the suggested results and hitting escape to get back to the
// original user query.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NavigateSuggestionsAndHitEscape) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("hello"));
  EXPECT_EQ("hello", GetOmniboxText());

  SendDownArrow();
  EXPECT_EQ("result 1", GetOmniboxText());
  SendDownArrow();
  EXPECT_EQ("result 2", GetOmniboxText());
  SendEscape();
  EXPECT_EQ("hello", GetOmniboxText());

  // Ensure that the API's value is set correctly.
  std::string result;
  EXPECT_TRUE(GetStringFromJS(instant()->GetOverlayContents(),
                              "window.chrome.searchBox.value",
                              &result));
  EXPECT_EQ("hello", result);

  EXPECT_TRUE(HasUserInputInProgress());
  EXPECT_FALSE(HasTemporaryText());

  // Commit the search by pressing Enter.
  browser()->window()->GetLocationBar()->AcceptInput();
  EXPECT_EQ("hello", GetOmniboxText());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PressEscapeWithBlueText) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Set blue text completion.
  EXPECT_TRUE(ExecuteScript("suggestion = 'chimichanga.com';"
                            "behavior = 1;"));

  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("chimi"));

  EXPECT_EQ(ASCIIToUTF16("chimichanga.com"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16("changa.com"), GetBlueText());
  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());

  EXPECT_TRUE(ExecuteScript("onChangeCalls = onNativeSuggestionsCalls = 0;"));

  SendDownArrow();

  EXPECT_EQ(ASCIIToUTF16("result 1"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16(""), GetBlueText());
  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());

  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_INSTANT_SET_SUGGESTION,
      content::NotificationService::AllSources());
  SendEscape();
  observer.Wait();

  EXPECT_EQ(ASCIIToUTF16("chimichanga.com"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16("changa.com"), GetBlueText());
  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());

  EXPECT_TRUE(UpdateSearchState(instant()->GetOverlayContents()));
  EXPECT_EQ(0, on_native_suggestions_calls_);
  EXPECT_EQ(0, on_change_calls_);
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PressEscapeWithGrayText) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Set gray text completion.
  EXPECT_TRUE(ExecuteScript("suggestion = 'cowabunga';"
                            "behavior = 2;"));

  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("cowa"));

  EXPECT_EQ(ASCIIToUTF16("cowa"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16(""), GetBlueText());
  EXPECT_EQ(ASCIIToUTF16("bunga"), GetGrayText());

  EXPECT_TRUE(ExecuteScript("onChangeCalls = onNativeSuggestionsCalls = 0;"));

  SendDownArrow();

  EXPECT_EQ(ASCIIToUTF16("result 1"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16(""), GetBlueText());
  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());

  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_INSTANT_SET_SUGGESTION,
      content::NotificationService::AllSources());
  SendEscape();
  observer.Wait();

  EXPECT_EQ(ASCIIToUTF16("cowa"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16(""), GetBlueText());
  EXPECT_EQ(ASCIIToUTF16("bunga"), GetGrayText());

  EXPECT_TRUE(UpdateSearchState(instant()->GetOverlayContents()));
  EXPECT_EQ(0, on_native_suggestions_calls_);
  EXPECT_EQ(0, on_change_calls_);
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NTPIsPreloaded) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // NTP contents should be preloaded.
  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
  content::WebContents* ntp_contents = instant()->ntp_->contents();
  EXPECT_TRUE(ntp_contents);
}

// Test that the local NTP is preloaded.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, LocalOnlyNTPIsPreloaded) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));

  // The second argument says to use only the local overlay and NTP.
  instant()->SetInstantEnabled(false, true);
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // NTP contents should be preloaded.
  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
  content::WebContents* ntp_contents = instant()->ntp_->contents();
  EXPECT_NE(static_cast<content::WebContents*>(NULL), ntp_contents);
  EXPECT_TRUE(instant()->ntp()->IsLocal());
}

// Test that the local NTP is not preloaded.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, LocalOnlyNTPIsNotPreloaded) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  ASSERT_TRUE(base::FieldTrialList::CreateTrialsFromString(
      "InstantExtended/Group1 local_only:1 preload_local_only_ntp:0/"));

  // The second argument says to use only the local overlay and NTP.
  instant()->SetInstantEnabled(false, true);

  // NTP contents should not be preloaded.
  EXPECT_EQ(NULL, instant()->ntp());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPIsUsedInNewTab) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // NTP contents should be preloaded.
  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
  content::WebContents* ntp_contents = instant()->ntp_->contents();
  EXPECT_TRUE(ntp_contents);

  // Open new tab. Preloaded NTP contents should have been used.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(ntp_contents, active_tab);
  EXPECT_TRUE(chrome::IsInstantNTP(active_tab));
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPIsUsedInSameTab) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // NTP contents should be preloaded.
  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
  content::WebContents* ntp_contents = instant()->ntp_->contents();
  EXPECT_TRUE(ntp_contents);

  // Open new tab. Preloaded NTP contents should have been used.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      CURRENT_TAB,
      ui_test_utils::BROWSER_TEST_NONE);
  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(ntp_contents, active_tab);
  EXPECT_TRUE(chrome::IsInstantNTP(active_tab));
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPForWrongProvider) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // NTP contents should be preloaded.
  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
  content::WebContents* ntp_contents = instant()->ntp_->contents();
  EXPECT_TRUE(ntp_contents);
  GURL ntp_url = ntp_contents->GetURL();

  // Change providers.
  SetInstantURL("chrome://blank");

  // Open new tab. Preloaded NTP contents should have not been used.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_NE(ntp_url, active_tab->GetURL());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPRenderViewGone) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // NTP contents should be preloaded.
  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
  EXPECT_FALSE(instant()->ntp()->IsLocal());

  // NTP not reloaded after being killed.
  instant()->InstantPageRenderViewGone(instant()->ntp()->contents());
  EXPECT_EQ(NULL, instant()->ntp());

  // Open new tab. Should use local NTP.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(instant()->GetLocalInstantURL(), active_tab->GetURL().spec());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPDoesntSupportInstant) {
  // Setup Instant.
  GURL instant_url = test_server()->GetURL("files/empty.html?strk=1");
  InstantTestBase::Init(instant_url);
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // NTP contents should have fallen back to the local page.
  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
  EXPECT_TRUE(instant()->ntp()->IsLocal());

  // Open new tab. Should use local NTP.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(instant()->GetLocalInstantURL(), active_tab->GetURL().spec());
}

// Flaky, http://crbug.com/240852 .
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_OmniboxHasFocusOnNewTab) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Explicitly unfocus the omnibox.
  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
  EXPECT_FALSE(omnibox()->model()->has_focus());

  // Open new tab. Preloaded NTP contents should have been used.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);

  // Omnibox should have focus.
  EXPECT_TRUE(omnibox()->model()->has_focus());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OmniboxEmptyOnNewTabPage) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Open new tab. Preloaded NTP contents should have been used.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);

  // Omnibox should be empty.
  EXPECT_TRUE(omnibox()->GetText().empty());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NoFaviconOnNewTabPage) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Open new tab. Preloaded NTP contents should have been used.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);

  // No favicon should be shown.
  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  FaviconTabHelper* favicon_tab_helper =
      FaviconTabHelper::FromWebContents(active_tab);
  EXPECT_FALSE(favicon_tab_helper->ShouldDisplayFavicon());

  // Favicon should be shown off the NTP.
  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
  favicon_tab_helper = FaviconTabHelper::FromWebContents(active_tab);
  EXPECT_TRUE(favicon_tab_helper->ShouldDisplayFavicon());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, InputOnNTPDoesntShowOverlay) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));

  // Focus omnibox and confirm overlay isn't shown.
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(overlay);
  EXPECT_FALSE(instant()->IsOverlayingSearchResults());
  EXPECT_TRUE(instant()->model()->mode().is_default());

  // Navigate to the NTP. Should use preloaded contents.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      CURRENT_TAB,
      ui_test_utils::BROWSER_TEST_NONE);

  // Typing in the omnibox should not show the overlay.
  SetOmniboxText("query");
  EXPECT_FALSE(instant()->IsOverlayingSearchResults());
  EXPECT_TRUE(instant()->model()->mode().is_default());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, ProcessIsolation) {
  // Prior to setup, Instant has an overlay with a failed "google.com" load in
  // it, which is rendered in the dedicated Instant renderer process.
  //
  // TODO(sreeram): Fix this up when we stop doing crazy things on init.
  InstantService* instant_service =
        InstantServiceFactory::GetForProfile(browser()->profile());
  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);
#if !defined(OS_MACOSX)
  // The failed "google.com" load is deleted, which sometimes leads to the
  // process shutting down on Mac.
  EXPECT_EQ(1, instant_service->GetInstantProcessCount());
#endif

  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // The registered Instant render process should still exist.
  EXPECT_EQ(1, instant_service->GetInstantProcessCount());

  // And the Instant overlay and ntp should live inside it.
  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(instant_service->IsInstantProcess(
      overlay->GetRenderProcessHost()->GetID()));
  content::WebContents* ntp_contents = instant()->ntp_->contents();
  EXPECT_TRUE(instant_service->IsInstantProcess(
      ntp_contents->GetRenderProcessHost()->GetID()));

  // Navigating to the NTP should use the Instant render process.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      CURRENT_TAB,
      ui_test_utils::BROWSER_TEST_NONE);
  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_TRUE(instant_service->IsInstantProcess(
      active_tab->GetRenderProcessHost()->GetID()));

  // Navigating elsewhere should not use the Instant render process.
  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
  EXPECT_FALSE(instant_service->IsInstantProcess(
      active_tab->GetRenderProcessHost()->GetID()));
}

// Test that a search query will not be displayed for navsuggest queries.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       SearchQueryNotDisplayedForNavsuggest) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));

  // The second argument indicates to use only the local overlay and NTP.
  instant()->SetInstantEnabled(true, true);

  // Focus omnibox and confirm overlay isn't shown.
  FocusOmniboxAndWaitForInstantOverlaySupport();

  // Typing in the omnibox should show the overlay.
  SetOmniboxText("face");

  content::WebContents* overlay = instant()->GetOverlayContents();

  // Add a navsuggest suggestion.
  instant()->SetSuggestions(
      overlay,
      std::vector<InstantSuggestion>(
          1,
          InstantSuggestion(ASCIIToUTF16("http://facemash.com/"),
                            INSTANT_COMPLETE_NOW,
                            INSTANT_SUGGESTION_URL,
                            ASCIIToUTF16("face"),
                            kNoMatchIndex)));

  while (!omnibox()->model()->autocomplete_controller()->done()) {
    content::WindowedNotificationObserver autocomplete_observer(
        chrome::NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY,
        content::NotificationService::AllSources());
    autocomplete_observer.Wait();
  }

  EXPECT_TRUE(ExecuteScript(
      "var sorted = chrome.embeddedSearch.searchBox.nativeSuggestions.sort("
          "function (a,b) {"
            "return b.rankingData.relevance - a.rankingData.relevance;"
          "});"));

  int suggestions_count = -1;
  EXPECT_TRUE(GetIntFromJS(
      overlay, "sorted.length", &suggestions_count));
  ASSERT_GT(suggestions_count, 0);

  std::string type;
  EXPECT_TRUE(
      GetStringFromJS(overlay, "sorted[0].type", &type));
  ASSERT_EQ("navsuggest", type);

  bool is_search;
  EXPECT_TRUE(GetBoolFromJS(
      overlay, "!!sorted[0].is_search", &is_search));
  EXPECT_FALSE(is_search);
}

// Verification of fix for BUG=176365.  Ensure that each Instant WebContents in
// a tab uses a new BrowsingInstance, to avoid conflicts in the
// NavigationController.
// Flaky: http://crbug.com/177516
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_UnrelatedSiteInstance) {
  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Check that the uncommited ntp page and uncommited overlay have unrelated
  // site instances.
  // TODO(sreeram): |ntp_| is going away, so this check can be removed in the
  // future.
  content::WebContents* overlay = instant()->GetOverlayContents();
  content::WebContents* ntp_contents = instant()->ntp_->contents();
  EXPECT_FALSE(overlay->GetSiteInstance()->IsRelatedSiteInstance(
      ntp_contents->GetSiteInstance()));

  // Type a query and hit enter to get a results page.  The overlay becomes the
  // active tab.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("hello"));
  EXPECT_EQ("hello", GetOmniboxText());
  browser()->window()->GetLocationBar()->AcceptInput();
  content::WebContents* first_active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(first_active_tab, overlay);
  scoped_refptr<content::SiteInstance> first_site_instance =
      first_active_tab->GetSiteInstance();
  EXPECT_FALSE(first_site_instance->IsRelatedSiteInstance(
      ntp_contents->GetSiteInstance()));

  // Navigating elsewhere gets us off of the commited page.  The next
  // query will give us a new |overlay| which we will then commit.
  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));

  // Show and commit the new overlay.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("hello again"));
  EXPECT_EQ("hello again", GetOmniboxText());
  browser()->window()->GetLocationBar()->AcceptInput();
  content::WebContents* second_active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_NE(first_active_tab, second_active_tab);
  scoped_refptr<content::SiteInstance> second_site_instance =
      second_active_tab->GetSiteInstance();
  EXPECT_NE(first_site_instance, second_site_instance);
  EXPECT_FALSE(
      first_site_instance->IsRelatedSiteInstance(second_site_instance.get()));
}

// Tests that suggestions are sanity checked.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, ValidatesSuggestions) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Do not set gray text that is not a suffix of the query.
  EXPECT_TRUE(ExecuteScript("suggestion = 'potato';"
                            "behavior = 2;"));
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
  EXPECT_EQ(ASCIIToUTF16("query"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());

  omnibox()->RevertAll();

  // Do not set blue text that is not a valid URL completion.
  EXPECT_TRUE(ExecuteScript("suggestion = 'this is not a url!';"
                            "behavior = 1;"));
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("this is"));
  EXPECT_EQ(ASCIIToUTF16("this is"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());

  omnibox()->RevertAll();

  // Do not set gray text when blue text is already set.
  // First set up some blue text completion.
  EXPECT_TRUE(ExecuteScript("suggestion = 'www.example.com';"
                            "behavior = 1;"));
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("http://www.ex"));
  EXPECT_EQ(ASCIIToUTF16("http://www.example.com"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16("ample.com"), GetBlueText());

  // Now try to set gray text for the same query.
  EXPECT_TRUE(ExecuteScript("suggestion = 'www.example.com rocks';"
                            "behavior = 2;"));
  SetOmniboxText("http://www.ex");
  EXPECT_EQ(ASCIIToUTF16("http://www.example.com"), omnibox()->GetText());
  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());

  omnibox()->RevertAll();

  // Ignore an out-of-date blue text suggestion. (Simulates a laggy
  // SetSuggestion IPC by directly calling into InstantController.)
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("http://www.example.com/"));
  instant()->SetSuggestions(
      instant()->overlay()->contents(),
      std::vector<InstantSuggestion>(
          1,
          InstantSuggestion(ASCIIToUTF16("www.exa"),
                            INSTANT_COMPLETE_NOW,
                            INSTANT_SUGGESTION_URL,
                            ASCIIToUTF16("www.exa"),
                            kNoMatchIndex)));
  EXPECT_EQ(
      "http://www.example.com/",
      omnibox()->model()->result().default_match()->destination_url.spec());

  omnibox()->RevertAll();

  // TODO(samarth): uncomment after fixing crbug.com/191656.
  // Use an out-of-date blue text suggestion, if the text typed by the user is
  // contained in the suggestion.
  // ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("ex"));
  // instant()->SetSuggestions(
  //     instant()->overlay()->contents(),
  //     std::vector<InstantSuggestion>(
  //         1,
  //         InstantSuggestion(ASCIIToUTF16("www.example.com"),
  //                           INSTANT_COMPLETE_NOW,
  //                           INSTANT_SUGGESTION_URL,
  //                           ASCIIToUTF16("e"))));
  // EXPECT_EQ(
  //     "http://www.example.com/",
  //     omnibox()->model()->result().default_match()->destination_url.spec());

  // omnibox()->RevertAll();

  // When asked to suggest blue text in verbatim mode, suggest the exact
  // omnibox text rather than using the supplied suggestion text.
  EXPECT_TRUE(ExecuteScript("suggestion = 'www.example.com/q';"
                            "behavior = 1;"));
  SetOmniboxText("www.example.com/q");
  omnibox()->OnBeforePossibleChange();
  SetOmniboxText("www.example.com/");
  omnibox()->OnAfterPossibleChange();
  EXPECT_EQ(ASCIIToUTF16("www.example.com/"), omnibox()->GetText());
}

// Tests that a previous navigation suggestion is not discarded if it's not
// stale.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       NavigationSuggestionIsNotDiscarded) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Tell the page to send a URL suggestion.
  EXPECT_TRUE(ExecuteScript("suggestion = 'http://www.example.com';"
                            "behavior = 1;"));
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("exa"));
  EXPECT_EQ(ASCIIToUTF16("example.com"), omnibox()->GetText());
  SetOmniboxText("exam");
  EXPECT_EQ(ASCIIToUTF16("example.com"), omnibox()->GetText());

  // TODO(jered): Remove this after fixing OnBlur().
  omnibox()->RevertAll();
}

// TODO(dhollowa): Fix flakes.  http://crbug.com/179930.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_MostVisited) {
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_INSTANT_SENT_MOST_VISITED_ITEMS,
      content::NotificationService::AllSources());
  // Initialize Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Get a handle to the NTP and the current state of the JS.
  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
  content::WebContents* overlay = instant()->ntp_->contents();
  EXPECT_TRUE(overlay);
  EXPECT_TRUE(UpdateSearchState(overlay));

  // Wait for most visited data to be ready, if necessary.
  if (on_most_visited_change_calls_ == 0) {
    observer.Wait();
    EXPECT_TRUE(UpdateSearchState(overlay));
  }

  EXPECT_EQ(1, on_most_visited_change_calls_);

  // Make sure we have at least two Most Visited Items and save that number.
  // TODO(pedrosimonetti): For now, we're relying on the fact that the Top
  // Sites will have at lease two items in it. The correct approach would be
  // adding those items to the Top Sites manually before starting the test.
  EXPECT_GT(most_visited_items_count_, 1);
  int old_most_visited_items_count = most_visited_items_count_;

  // Delete the fist Most Visited Item.
  int rid = first_most_visited_item_id_;
  std::ostringstream stream;
  stream << "newTabPageHandle.deleteMostVisitedItem(" << rid << ");";
  EXPECT_TRUE(ExecuteScript(stream.str()));
  observer.Wait();

  // Update Most Visited state.
  EXPECT_TRUE(UpdateSearchState(overlay));

  // Make sure we have one less item in there.
  EXPECT_EQ(most_visited_items_count_, old_most_visited_items_count - 1);

  // Undo the deletion of the fist Most Visited Item.
  stream.str(std::string());
  stream << "newTabPageHandle.undoMostVisitedDeletion(" << rid << ");";
  EXPECT_TRUE(ExecuteScript(stream.str()));
  observer.Wait();

  // Update Most Visited state.
  EXPECT_TRUE(UpdateSearchState(overlay));

  // Make sure we have the same number of items as before.
  EXPECT_EQ(most_visited_items_count_, old_most_visited_items_count);

  // Delete the fist Most Visited Item.
  rid = first_most_visited_item_id_;
  stream.str(std::string());
  stream << "newTabPageHandle.deleteMostVisitedItem(" << rid << ");";
  EXPECT_TRUE(ExecuteScript(stream.str()));
  observer.Wait();

  // Update Most Visited state.
  EXPECT_TRUE(UpdateSearchState(overlay));

  // Delete the second Most Visited Item.
  rid = first_most_visited_item_id_;
  stream.str(std::string());
  stream << "newTabPageHandle.deleteMostVisitedItem(" << rid << ");";
  EXPECT_TRUE(ExecuteScript(stream.str()));
  observer.Wait();

  // Update Most Visited state.
  EXPECT_TRUE(UpdateSearchState(overlay));

  // Make sure we have two less items in there.
  EXPECT_EQ(most_visited_items_count_, old_most_visited_items_count - 2);

  // Delete the second Most Visited Item.
  stream.str(std::string());
  stream << "newTabPageHandle.undoAllMostVisitedDeletions();";
  EXPECT_TRUE(ExecuteScript(stream.str()));
  observer.Wait();

  // Update Most Visited state.
  EXPECT_TRUE(UpdateSearchState(overlay));

  // Make sure we have the same number of items as before.
  EXPECT_EQ(most_visited_items_count_, old_most_visited_items_count);
}

IN_PROC_BROWSER_TEST_F(InstantPolicyTest, ThemeBackgroundAccess) {
  InstallThemeSource();
  ASSERT_NO_FATAL_FAILURE(InstallThemeAndVerify("theme", "camo theme"));
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // The "Instant" New Tab should have access to chrome-search: scheme but not
  // chrome: scheme.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_NONE);

  content::RenderViewHost* rvh =
      browser()->tab_strip_model()->GetActiveWebContents()->GetRenderViewHost();

  const std::string chrome_url("chrome://theme/IDR_THEME_NTP_BACKGROUND");
  const std::string search_url(
      "chrome-search://theme/IDR_THEME_NTP_BACKGROUND");
  bool loaded = false;
  ASSERT_TRUE(LoadImage(rvh, chrome_url, &loaded));
  EXPECT_FALSE(loaded) << chrome_url;
  ASSERT_TRUE(LoadImage(rvh, search_url, &loaded));
  EXPECT_TRUE(loaded) << search_url;
}

// TODO(dhollowa): Fix flakes.  http://crbug.com/179930.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_FaviconAccess) {
  // Create a favicon.
  history::TopSites* top_sites = browser()->profile()->GetTopSites();
  GURL url("http://www.google.com/foo.html");
  gfx::Image thumbnail(CreateBitmap(SK_ColorWHITE));
  ThumbnailScore high_score(0.0, true, true, base::Time::Now());
  EXPECT_TRUE(top_sites->SetPageThumbnail(url, thumbnail, high_score));

  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // The "Instant" New Tab should have access to chrome-search: scheme but not
  // chrome: scheme.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);

  content::RenderViewHost* rvh =
      browser()->tab_strip_model()->GetActiveWebContents()->GetRenderViewHost();

  // Get the favicons.
  const std::string chrome_favicon_url(
      "chrome://favicon/largest/http://www.google.com/foo.html");
  const std::string search_favicon_url(
      "chrome-search://favicon/largest/http://www.google.com/foo.html");
  bool loaded = false;
  ASSERT_TRUE(LoadImage(rvh, chrome_favicon_url, &loaded));
  EXPECT_FALSE(loaded) << chrome_favicon_url;
  ASSERT_TRUE(LoadImage(rvh, search_favicon_url, &loaded));
  EXPECT_TRUE(loaded) << search_favicon_url;
}

// WebUIBindings should never be enabled on ANY Instant web contents.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NoWebUIBindingsOnNTP) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
  const content::WebContents* tab =
      browser()->tab_strip_model()->GetActiveWebContents();

  // Instant-provided NTP should not have any bindings enabled.
  EXPECT_EQ(0, tab->GetRenderViewHost()->GetEnabledBindings());
}

// WebUIBindings should never be enabled on ANY Instant web contents.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NoWebUIBindingsOnPreview) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Typing in the omnibox shows the overlay.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
  EXPECT_TRUE(instant()->model()->mode().is_search_suggestions());
  content::WebContents* preview = instant()->GetOverlayContents();
  ASSERT_NE(static_cast<content::WebContents*>(NULL), preview);

  // Instant preview should not have any bindings enabled.
  EXPECT_EQ(0, preview->GetRenderViewHost()->GetEnabledBindings());
}

// WebUIBindings should never be enabled on ANY Instant web contents.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NoWebUIBindingsOnResults) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Typing in the omnibox shows the overlay.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
  content::WebContents* preview = instant()->GetOverlayContents();
  EXPECT_TRUE(instant()->model()->mode().is_search_suggestions());
  // Commit the search by pressing Enter.
  browser()->window()->GetLocationBar()->AcceptInput();
  EXPECT_TRUE(instant()->model()->mode().is_default());
  const content::WebContents* tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(preview, tab);

  // The commited Instant page should not have any bindings enabled.
  EXPECT_EQ(0, tab->GetRenderViewHost()->GetEnabledBindings());
}

// Only implemented in Views and Mac currently: http://crbug.com/164723
#if defined(OS_WIN) || defined(OS_CHROMEOS) || defined(OS_MACOSX)
#define MAYBE_HomeButtonAffectsMargin HomeButtonAffectsMargin
#else
#define MAYBE_HomeButtonAffectsMargin DISABLED_HomeButtonAffectsMargin
#endif
// Check that toggling the state of the home button changes the start-edge
// margin and width.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, MAYBE_HomeButtonAffectsMargin) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlaySupport();

  // Get the current value of the start-edge margin and width.
  int start_margin;
  int width;
  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(GetIntFromJS(overlay, "chrome.searchBox.startMargin",
      &start_margin));
  EXPECT_TRUE(GetIntFromJS(overlay, "chrome.searchBox.width", &width));

  // Toggle the home button visibility pref.
  PrefService* profile_prefs = browser()->profile()->GetPrefs();
  bool show_home = profile_prefs->GetBoolean(prefs::kShowHomeButton);
  profile_prefs->SetBoolean(prefs::kShowHomeButton, !show_home);

  // Make sure the margin and width changed.
  int new_start_margin;
  int new_width;
  EXPECT_TRUE(GetIntFromJS(overlay, "chrome.searchBox.startMargin",
      &new_start_margin));
  EXPECT_TRUE(GetIntFromJS(overlay, "chrome.searchBox.width", &new_width));
  EXPECT_NE(start_margin, new_start_margin);
  EXPECT_NE(width, new_width);
  EXPECT_EQ(new_width - width, start_margin - new_start_margin);
}

// Commit does not happen on Mac: http://crbug.com/178520
#if defined(OS_MACOSX)
#define MAYBE_CommitWhenFocusLostInFullHeight \
        DISABLED_CommitWhenFocusLostInFullHeight
#else
#define MAYBE_CommitWhenFocusLostInFullHeight CommitWhenFocusLostInFullHeight
#endif
// Test that the overlay is committed when the omnibox loses focus when it is
// shown at 100% height.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       MAYBE_CommitWhenFocusLostInFullHeight) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));

  // Focus omnibox and confirm overlay isn't shown.
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(overlay);
  EXPECT_TRUE(instant()->model()->mode().is_default());
  EXPECT_FALSE(instant()->IsOverlayingSearchResults());

  // Typing in the omnibox should show the overlay.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
  EXPECT_TRUE(instant()->IsOverlayingSearchResults());
  EXPECT_EQ(overlay, instant()->GetOverlayContents());

  // Explicitly unfocus the omnibox without triggering a click. Note that this
  // doesn't actually change the focus state of the omnibox, only what the
  // Instant controller sees it as.
  omnibox()->model()->OnWillKillFocus(NULL);
  omnibox()->model()->OnKillFocus();

  // Confirm that the overlay has been committed.
  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(overlay, active_tab);
}

#if defined(OS_MACOSX)
// http://crbug.com/227076
#define MAYBE_CommitWhenShownInFullHeightWithoutFocus \
        DISABLED_CommitWhenShownInFullHeightWithoutFocus
#else
#define MAYBE_CommitWhenShownInFullHeightWithoutFocus \
        CommitWhenShownInFullHeightWithoutFocus
#endif

// Test that the overlay is committed when shown at 100% height without focus
// in the omnibox.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       MAYBE_CommitWhenShownInFullHeightWithoutFocus) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));

  // Focus omnibox and confirm overlay isn't shown.
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(overlay);
  EXPECT_TRUE(instant()->model()->mode().is_default());
  EXPECT_FALSE(instant()->IsOverlayingSearchResults());

  // Create an observer to wait for the commit.
  content::WindowedNotificationObserver commit_observer(
      chrome::NOTIFICATION_INSTANT_COMMITTED,
      content::NotificationService::AllSources());

  // Create an observer to wait for the autocomplete.
  content::WindowedNotificationObserver autocomplete_observer(
      chrome::NOTIFICATION_INSTANT_SENT_AUTOCOMPLETE_RESULTS,
      content::NotificationService::AllSources());

  // Typing in the omnibox should show the overlay. Don't wait for the overlay
  // to show however.
  SetOmniboxText("query");

  autocomplete_observer.Wait();

  // Explicitly unfocus the omnibox without triggering a click. Note that this
  // doesn't actually change the focus state of the omnibox, only what the
  // Instant controller sees it as.
  omnibox()->model()->OnWillKillFocus(NULL);
  omnibox()->model()->OnKillFocus();

  // Wait for the overlay to show.
  commit_observer.Wait();

  // Confirm that the overlay has been committed.
  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(overlay, active_tab);
}

// Test that a transient entry is set properly when the overlay is committed
// without a navigation.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, TransientEntrySet) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));

  // Focus omnibox and confirm overlay isn't shown.
  FocusOmniboxAndWaitForInstantOverlaySupport();
  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(overlay);
  EXPECT_TRUE(instant()->model()->mode().is_default());
  EXPECT_FALSE(instant()->IsOverlayingSearchResults());

  // Commit the overlay without triggering a navigation.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_INSTANT_COMMITTED,
      content::NotificationService::AllSources());
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
  browser()->window()->GetLocationBar()->AcceptInput();
  observer.Wait();

  // Confirm that the overlay has been committed.
  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(overlay, active_tab);

  // The page hasn't navigated so there should be a transient entry with the
  // same URL but different page ID as the last committed entry.
  const content::NavigationEntry* transient_entry =
      active_tab->GetController().GetTransientEntry();
  const content::NavigationEntry* committed_entry =
      active_tab->GetController().GetLastCommittedEntry();
  EXPECT_EQ(transient_entry->GetURL(), committed_entry->GetURL());
  EXPECT_NE(transient_entry->GetPageID(), committed_entry->GetPageID());
}

// Test that the a transient entry is cleared when the overlay is committed
// with a navigation.
// TODO(samarth) : this test fails, http://crbug.com/181070.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_TransientEntryRemoved) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));

  // Focus omnibox and confirm overlay isn't shown.
  FocusOmniboxAndWaitForInstantOverlaySupport();
  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(overlay);
  EXPECT_TRUE(instant()->model()->mode().is_default());
  EXPECT_FALSE(instant()->IsOverlayingSearchResults());

  // Create an observer to wait for the commit.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_INSTANT_COMMITTED,
      content::NotificationService::AllSources());

  // Trigger a navigation on commit.
  EXPECT_TRUE(ExecuteScript(
      "getApiHandle().oncancel = function() {"
      "  location.replace(location.href + '#q=query');"
      "};"
      ));

  // Commit the overlay.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
  browser()->window()->GetLocationBar()->AcceptInput();
  observer.Wait();

  // Confirm that the overlay has been committed.
  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(overlay, active_tab);

  // The page has navigated so there should be no transient entry.
  const content::NavigationEntry* transient_entry =
      active_tab->GetController().GetTransientEntry();
  EXPECT_EQ(NULL, transient_entry);

  // The last committed entry should be the URL the page navigated to.
  const content::NavigationEntry* committed_entry =
      active_tab->GetController().GetLastCommittedEntry();
  EXPECT_TRUE(EndsWith(committed_entry->GetURL().spec(), "#q=query", true));
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, RestrictedURLReading) {
  std::string search_query;
  bool is_undefined;
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlaySupport();

  // Verify we can read out something ok.
  const char kOKQuery[] = "santa";
  SetOmniboxText(kOKQuery);
  EXPECT_EQ(ASCIIToUTF16(kOKQuery), omnibox()->GetText());
  // Must always assert the value is defined before trying to read it, as trying
  // to read undefined values causes the test to hang.
  EXPECT_TRUE(GetBoolFromJS(instant()->GetOverlayContents(),
                            "apiHandle.value === undefined",
                            &is_undefined));
  ASSERT_FALSE(is_undefined);
  EXPECT_TRUE(GetStringFromJS(instant()->GetOverlayContents(),
                              "apiHandle.value",
                              &search_query));
  EXPECT_EQ(kOKQuery, search_query);

  // Verify we can't read out something that should be restricted, like a https
  // url with a path.
  const char kHTTPSUrlWithPath[] = "https://www.example.com/foobar";
  SetOmniboxText(kHTTPSUrlWithPath);
  EXPECT_EQ(ASCIIToUTF16(kHTTPSUrlWithPath), omnibox()->GetText());
  EXPECT_TRUE(GetBoolFromJS(instant()->GetOverlayContents(),
                            "apiHandle.value === undefined",
                            &is_undefined));
  EXPECT_TRUE(is_undefined);
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, RestrictedItemReadback) {
  // Initialize Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlaySupport();

  // Get a handle to the NTP and the current state of the JS.
  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
  content::WebContents* preview_tab = instant()->ntp()->contents();
  EXPECT_TRUE(preview_tab);

  // Manufacture a few autocomplete results and get them down to the page.
  std::vector<InstantAutocompleteResult> autocomplete_results;
  for (int i = 0; i < 3; ++i) {
    std::string description(base::StringPrintf("Test Description %d", i));
    std::string url(base::StringPrintf("http://www.testurl%d.com", i));

    InstantAutocompleteResult res;
    res.provider = ASCIIToUTF16(AutocompleteProvider::TypeToString(
        AutocompleteProvider::TYPE_BUILTIN));
    res.type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
    res.description = ASCIIToUTF16(description);
    res.destination_url = ASCIIToUTF16(url);
    res.transition = content::PAGE_TRANSITION_TYPED;
    res.relevance = 42 + i;

    autocomplete_results.push_back(res);
  }
  instant()->overlay()->SendAutocompleteResults(autocomplete_results);

  // Apparently, one needs to access nativeSuggestions before
  // apiHandle.setRestrictedValue can work.
  EXPECT_TRUE(ExecuteScript("var foo = apiHandle.nativeSuggestions;"));

  const char kQueryString[] = "Hippos go berzerk!";

  // First set the query text to a non restricted value and ensure it can be
  // read back.
  std::ostringstream stream;
  stream << "apiHandle.setValue('" << kQueryString << "');";
  EXPECT_TRUE(ExecuteScript(stream.str()));

  std::string query_string;
  bool is_undefined;
  EXPECT_TRUE(GetStringFromJS(instant()->GetOverlayContents(),
                              "apiHandle.value",
                              &query_string));
  EXPECT_EQ(kQueryString, query_string);

  // Set the query text to the first restricted autocomplete item.
  int rid = 1;
  stream.str(std::string());
  stream << "apiHandle.setRestrictedValue(" << rid << ");";
  EXPECT_TRUE(ExecuteScript(stream.str()));

  // Expect that we now receive undefined when reading the value back.
  EXPECT_TRUE(GetBoolFromJS(
      instant()->GetOverlayContents(),
      "apiHandle.value === undefined",
      &is_undefined));
  EXPECT_TRUE(is_undefined);

  // Now set the query text to a non restricted value and ensure that the
  // visibility has been reset and the string can again be read back.
  stream.str(std::string());
  stream << "apiHandle.setValue('" << kQueryString << "');";
  EXPECT_TRUE(ExecuteScript(stream.str()));

  EXPECT_TRUE(GetStringFromJS(instant()->GetOverlayContents(),
                              "apiHandle.value",
                              &query_string));
  EXPECT_EQ(kQueryString, query_string);
}

// Test that autocomplete results are sent to the page only when all the
// providers are done.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, AutocompleteProvidersDone) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(UpdateSearchState(overlay));
  EXPECT_EQ(0, on_native_suggestions_calls_);

  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("railroad"));

  EXPECT_EQ(overlay, instant()->GetOverlayContents());
  EXPECT_TRUE(UpdateSearchState(overlay));
  EXPECT_EQ(1, on_native_suggestions_calls_);
}

// Test that the Bookmark provider is enabled, and returns results.
// TODO(sreeram): Convert this to a unit test.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_HasBookmarkProvider) {
  // No need to setup Instant.
  set_browser(browser());

  BookmarkModel* bookmark_model =
      BookmarkModelFactory::GetForProfile(browser()->profile());
  ASSERT_TRUE(bookmark_model);
  ui_test_utils::WaitForBookmarkModelToLoad(bookmark_model);
  bookmark_utils::AddIfNotBookmarked(bookmark_model, GURL("http://angeline/"),
                                     ASCIIToUTF16("angeline"));

  SetOmniboxText("angeline");

  bool found_bookmark_match = false;

  const AutocompleteResult& result = omnibox()->model()->result();
  for (AutocompleteResult::const_iterator iter = result.begin();
       !found_bookmark_match && iter != result.end(); ++iter) {
    found_bookmark_match = iter->type == AutocompleteMatchType::BOOKMARK_TITLE;
  }

  EXPECT_TRUE(found_bookmark_match);
}

// Test that the omnibox's temporary text is reset when the popup is closed.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, TemporaryTextResetWhenPopupClosed) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  // Show the overlay and arrow-down to a suggestion (this sets temporary text).
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("juju"));
  SendDownArrow();

  EXPECT_TRUE(HasTemporaryText());
  EXPECT_EQ("result 1", GetOmniboxText());

  // Click outside the omnibox (but not on the overlay), to make the omnibox
  // lose focus. Close the popup explicitly, to workaround test/toolkit issues.
  ui_test_utils::ClickOnView(browser(), VIEW_ID_TOOLBAR);
  omnibox()->CloseOmniboxPopup();

  // The temporary text should've been accepted as the user text.
  EXPECT_FALSE(HasTemporaryText());
  EXPECT_EQ("result 1", GetOmniboxText());

  // Now refocus the omnibox and hit Escape. This shouldn't crash.
  FocusOmnibox();
  SendEscape();

  // The omnibox should've reverted to the underlying permanent URL.
  EXPECT_FALSE(HasTemporaryText());
  EXPECT_EQ(std::string(content::kAboutBlankURL), GetOmniboxText());
}

// Test that autocomplete results aren't sent when the popup is closed.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       NoAutocompleteResultsWhenPopupClosed) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  // Show the overlay and arrow-down to a suggestion (this sets temporary text).
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("thangam"));
  SendDownArrow();
  EXPECT_TRUE(HasTemporaryText());

  EXPECT_TRUE(ExecuteScript("onChangeCalls = onNativeSuggestionsCalls = 0;"));

  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(UpdateSearchState(overlay));
  EXPECT_EQ(0, on_change_calls_);
  EXPECT_EQ(0, on_native_suggestions_calls_);

  // Click outside the omnibox (but not on the overlay), to make the omnibox
  // lose focus. Close the popup explicitly, to workaround test/toolkit issues.
  ui_test_utils::ClickOnView(browser(), VIEW_ID_TOOLBAR);
  omnibox()->CloseOmniboxPopup();
  EXPECT_FALSE(HasTemporaryText());

  EXPECT_EQ(overlay, instant()->GetOverlayContents());
  EXPECT_TRUE(UpdateSearchState(overlay));
  EXPECT_EQ(0, on_change_calls_);
  EXPECT_EQ(0, on_native_suggestions_calls_);
}

// Test that suggestions are not accepted when unexpected.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DeniesUnexpectedSuggestions) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("chip"));
  SendDownArrow();

  EXPECT_EQ("result 1", GetOmniboxText());
  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());

  // Make the page send an unexpected suggestion.
  EXPECT_TRUE(ExecuteScript("suggestion = 'chippies';"
                            "handleOnChange();"));

  // Verify that the suggestion is ignored.
  EXPECT_EQ("result 1", GetOmniboxText());
  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());
}

// Test that autocomplete results are cleared when the query is cleared.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, EmptyAutocompleteResults) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Type a URL, so that there's at least one autocomplete result (a "URL what
  // you typed" match).
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("http://upsamina/"));

  content::WebContents* overlay = instant()->GetOverlayContents();

  int num_autocomplete_results = 0;
  EXPECT_TRUE(GetIntFromJS(
      overlay,
      "chrome.embeddedSearch.searchBox.nativeSuggestions.length",
      &num_autocomplete_results));
  EXPECT_LT(0, num_autocomplete_results);

  // Erase the query in the omnibox.
  SetOmniboxText("");

  EXPECT_TRUE(GetIntFromJS(
      overlay,
      "chrome.embeddedSearch.searchBox.nativeSuggestions.length",
      &num_autocomplete_results));
  EXPECT_EQ(0, num_autocomplete_results);
}

// Test that hitting Esc to clear the omnibox works. http://crbug.com/231744.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, EscapeClearsOmnibox) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Navigate to the Instant NTP, and wait for it to be recognized.
  content::WindowedNotificationObserver instant_tab_observer(
      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
      content::NotificationService::AllSources());
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
  instant_tab_observer.Wait();

  content::WebContents* contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  // Type a query. Verify that the query is seen by the page.
  SetOmniboxText("mojo");
  std::string query;
  EXPECT_TRUE(GetStringFromJS(contents, "chrome.embeddedSearch.searchBox.value",
                              &query));
  EXPECT_EQ("mojo", query);

  EXPECT_TRUE(content::ExecuteScript(contents,
                                     "onChangeCalls = submitCount = 0;"));

  // Hit Escape, and verify that the page sees that the query is cleared.
  SendEscape();
  EXPECT_TRUE(GetStringFromJS(contents, "chrome.embeddedSearch.searchBox.value",
                              &query));
  EXPECT_EQ("", query);
  EXPECT_EQ("", GetOmniboxText());

  EXPECT_TRUE(UpdateSearchState(contents));
  EXPECT_LT(0, on_change_calls_);
  EXPECT_EQ(0, submit_count_);
  EXPECT_LT(0, on_esc_key_press_event_calls_);
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, FocusApiRespondsToFocusChange) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
  EXPECT_FALSE(is_focused_);
  EXPECT_EQ(0, on_focus_changed_calls_);

  // Focus the omnibox.
  FocusOmniboxAndWaitForInstantOverlaySupport();
  ASSERT_TRUE(UpdateSearchState(instant()->GetOverlayContents()));
  EXPECT_TRUE(is_focused_);
  EXPECT_EQ(1, on_focus_changed_calls_);

  // Now unfocus the omnibox.
  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
  ASSERT_TRUE(UpdateSearchState(instant()->GetOverlayContents()));
  EXPECT_FALSE(is_focused_);
  EXPECT_EQ(2, on_focus_changed_calls_);

  // Focus the omnibox again.
  // The first focus may have worked only due to initial-state anomalies.
  FocusOmnibox();
  ASSERT_TRUE(UpdateSearchState(instant()->GetOverlayContents()));
  EXPECT_TRUE(is_focused_);
  EXPECT_EQ(3, on_focus_changed_calls_);
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, FocusApiIgnoresRedundantFocus) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
  EXPECT_FALSE(is_focused_);
  EXPECT_EQ(0, on_focus_changed_calls_);

  // Focus the Omnibox.
  FocusOmniboxAndWaitForInstantOverlaySupport();
  ASSERT_TRUE(UpdateSearchState(instant()->GetOverlayContents()));
  EXPECT_TRUE(is_focused_);
  EXPECT_EQ(1, on_focus_changed_calls_);

  // When we focus the omnibox again, nothing should change.
  FocusOmnibox();
  ASSERT_TRUE(UpdateSearchState(instant()->GetOverlayContents()));
  EXPECT_TRUE(is_focused_);
  EXPECT_EQ(1, on_focus_changed_calls_);

  // Now unfocus the omnibox.
  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
  ASSERT_TRUE(UpdateSearchState(instant()->GetOverlayContents()));
  EXPECT_FALSE(is_focused_);
  EXPECT_EQ(2, on_focus_changed_calls_);

  // When we unfocus again, nothing should change.
  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
  ASSERT_TRUE(UpdateSearchState(instant()->GetOverlayContents()));
  EXPECT_FALSE(is_focused_);
  EXPECT_EQ(2, on_focus_changed_calls_);
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OnDefaultSearchProviderChanged) {
  InstantService* instant_service =
      InstantServiceFactory::GetForProfile(browser()->profile());
  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);

  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  EXPECT_EQ(1, instant_service->GetInstantProcessCount());

  // Navigating to the NTP should use the Instant render process.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      CURRENT_TAB,
      ui_test_utils::BROWSER_TEST_NONE);
  content::WebContents* ntp_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_TRUE(chrome::IsInstantNTP(ntp_contents));
  EXPECT_TRUE(instant_service->IsInstantProcess(
      ntp_contents->GetRenderProcessHost()->GetID()));
  GURL ntp_url = ntp_contents->GetURL();

  AddBlankTabAndShow(browser());
  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_FALSE(chrome::IsInstantNTP(active_tab));
  EXPECT_FALSE(instant_service->IsInstantProcess(
      active_tab->GetRenderProcessHost()->GetID()));

  TemplateURLData data;
  data.short_name = ASCIIToUTF16("t");
  data.SetURL("http://defaultturl/q={searchTerms}");
  data.suggestions_url = "http://defaultturl2/q={searchTerms}";
  data.instant_url = "http://does/not/exist";
  data.alternate_urls.push_back(data.instant_url + "#q={searchTerms}");
  data.search_terms_replacement_key = "strk";

  TemplateURL* template_url = new TemplateURL(browser()->profile(), data);
  TemplateURLService* service =
      TemplateURLServiceFactory::GetForProfile(browser()->profile());
  ui_test_utils::WaitForTemplateURLServiceToLoad(service);
  service->Add(template_url);  // Takes ownership of |template_url|.

  // Change the default search provider.
  content::WindowedNotificationObserver observer(
      content::NOTIFICATION_LOAD_STOP,
      content::Source<content::NavigationController>(
          &ntp_contents->GetController()));
  service->SetDefaultSearchProvider(template_url);
  observer.Wait();

  // |ntp_contents| should not use the Instant render process.
  EXPECT_FALSE(chrome::IsInstantNTP(ntp_contents));
  EXPECT_FALSE(instant_service->IsInstantProcess(
      ntp_contents->GetRenderProcessHost()->GetID()));
  // Make sure the URL remains the same.
  EXPECT_EQ(ntp_url, ntp_contents->GetURL());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OverlayRenderViewGone) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  EXPECT_NE(static_cast<content::WebContents*>(NULL),
            instant()->GetOverlayContents());

  // Overlay is not reloaded after being killed.
  EXPECT_FALSE(instant()->overlay()->IsLocal());
  instant()->InstantPageRenderViewGone(instant()->GetOverlayContents());
  EXPECT_EQ(NULL, instant()->GetOverlayContents());

  // The local overlay is used on the next Update().
  SetOmniboxText("query");
  EXPECT_TRUE(instant()->overlay()->IsLocal());

  // Switched back to the remote overlay when omnibox loses and regains focus.
  instant()->HideOverlay();
  browser()->tab_strip_model()->GetActiveWebContents()->GetView()->Focus();
  FocusOmnibox();
  EXPECT_FALSE(instant()->overlay()->IsLocal());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OverlayDoesntSupportInstant) {
  GURL instant_url = test_server()->GetURL("files/empty.html?strk=1");
  InstantTestBase::Init(instant_url);
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));

  // Focus the omnibox. When the support determination response comes back,
  // Instant will destroy the non-Instant page and fall back to the local page.
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  ASSERT_NE(static_cast<InstantOverlay*>(NULL), instant()->overlay());
  EXPECT_TRUE(instant()->overlay()->IsLocal());

  // The local overlay is used on the next Update().
  SetOmniboxText("query");
  EXPECT_TRUE(instant()->overlay()->IsLocal());

  // Switched back to the remote overlay when omnibox loses and regains focus.
  instant()->HideOverlay();
  browser()->tab_strip_model()->GetActiveWebContents()->GetView()->Focus();
  FocusOmnibox();
  EXPECT_FALSE(instant()->overlay()->IsLocal());

  // Overlay falls back to local again after determining support.
  FocusOmniboxAndWaitForInstantOverlaySupport();
  ASSERT_NE(static_cast<InstantOverlay*>(NULL), instant()->overlay());
  EXPECT_TRUE(instant()->overlay()->IsLocal());
}

// Test that if Instant alters the input from URL to search, it's respected.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, InputChangedFromURLToSearch) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(ExecuteScript("suggestions = ['mcqueen.com'];"));

  SetOmniboxTextAndWaitForOverlayToShow("lightning");
  EXPECT_EQ("lightning", GetOmniboxText());

  SendDownArrow();
  EXPECT_EQ("mcqueen.com", GetOmniboxText());

  // Press Enter.
  browser()->window()->GetLocationBar()->AcceptInput();

  // Confirm that the Instant overlay was committed.
  EXPECT_EQ(overlay, browser()->tab_strip_model()->GetActiveWebContents());
}

// Test that if Instant alters the input from search to URL, it's respected.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, InputChangedFromSearchToURL) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  content::WebContents* overlay = instant()->GetOverlayContents();
  EXPECT_TRUE(ExecuteScript("suggestionType = 1;"));  // INSTANT_SUGGESTION_URL

  SetOmniboxTextAndWaitForOverlayToShow("mack.com");
  EXPECT_EQ("mack.com", GetOmniboxText());

  SendDownArrow();
  EXPECT_EQ("result 1", GetOmniboxText());

  // Press Enter.
  browser()->window()->GetLocationBar()->AcceptInput();

  // Confirm that the Instant overlay was NOT committed.
  EXPECT_NE(overlay, browser()->tab_strip_model()->GetActiveWebContents());
}

// Test that renderer initiated navigations to an instant URL from a non
// Instant page do not end up in an Instant process if they are bounced to the
// browser.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       RendererInitiatedNavigationNotInInstantProcess) {
  InstantService* instant_service =
      InstantServiceFactory::GetForProfile(browser()->profile());
  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);

  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
  EXPECT_EQ(1, browser()->tab_strip_model()->count());

  // Don't use https server for the non instant URL so that the browser uses
  // different RenderViews.
  GURL non_instant_url = test_server()->GetURL("files/simple.html");
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      non_instant_url,
      CURRENT_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  content::WebContents* contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_FALSE(instant_service->IsInstantProcess(
      contents->GetRenderProcessHost()->GetID()));
  EXPECT_EQ(non_instant_url, contents->GetURL());

  int old_render_view_id = contents->GetRenderViewHost()->GetRoutingID();
  int old_render_process_id = contents->GetRenderProcessHost()->GetID();

  std::string instant_url_with_query = instant_url().spec() + "q=3";
  std::string add_link_script = base::StringPrintf(
      "var a = document.createElement('a');"
      "a.id = 'toClick';"
      "a.href = '%s';"
      "document.body.appendChild(a);",
      instant_url_with_query.c_str());
  EXPECT_TRUE(content::ExecuteScript(contents, add_link_script));

  // Ensure that navigations are bounced to the browser.
  contents->GetMutableRendererPrefs()->browser_handles_all_top_level_requests =
      true;
  contents->GetRenderViewHost()->SyncRendererPrefs();

  content::WindowedNotificationObserver observer(
        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
        content::NotificationService::AllSources());
  EXPECT_TRUE(content::ExecuteScript(
      contents, "document.getElementById('toClick').click();"));
  observer.Wait();

  EXPECT_EQ(1, browser()->tab_strip_model()->count());
  contents = browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_FALSE(instant_service->IsInstantProcess(
      contents->GetRenderProcessHost()->GetID()));
  EXPECT_EQ(GURL(instant_url_with_query), contents->GetURL());
  int new_render_view_id = contents->GetRenderViewHost()->GetRoutingID();
  int new_render_process_id = contents->GetRenderProcessHost()->GetID();

  EXPECT_TRUE(old_render_process_id != new_render_process_id ||
              old_render_view_id != new_render_view_id);
}

// Test that renderer initiated navigations to an Instant URL from an
// Instant process end up in an Instant process.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       RendererInitiatedNavigationInInstantProcess) {
  InstantService* instant_service =
      InstantServiceFactory::GetForProfile(browser()->profile());
  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);

  // Setup Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
  EXPECT_EQ(1, browser()->tab_strip_model()->count());

  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      instant_url(),
      CURRENT_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  content::WebContents* contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_TRUE(instant_service->IsInstantProcess(
      contents->GetRenderProcessHost()->GetID()));

  std::string instant_url_with_query = instant_url().spec() + "q=3";
  std::string add_link_script = base::StringPrintf(
      "var a = document.createElement('a');"
      "a.id = 'toClick';"
      "a.href = '%s';"
      "document.body.appendChild(a);",
      instant_url_with_query.c_str());
  EXPECT_TRUE(content::ExecuteScript(contents, add_link_script));

  content::WindowedNotificationObserver observer(
        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
        content::NotificationService::AllSources());
  EXPECT_TRUE(content::ExecuteScript(
      contents, "document.getElementById('toClick').click();"));
  observer.Wait();

  EXPECT_EQ(1, browser()->tab_strip_model()->count());
  contents = browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_TRUE(instant_service->IsInstantProcess(
      contents->GetRenderProcessHost()->GetID()));
  EXPECT_EQ(GURL(instant_url_with_query), contents->GetURL());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, SearchProviderDoesntRun) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlaySupport();

  // Add "query" to history.
  ASSERT_TRUE(AddSearchToHistory(ASCIIToUTF16("query"), 10000));
  BlockUntilHistoryProcessesPendingRequests();

  SetOmniboxText("quer");

  // Should get only SWYT from SearchProvider.
  EXPECT_EQ(1, CountSearchProviderSuggestions());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, SearchProviderRunsForLocalOnly) {
  // Force local-only Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  instant()->SetInstantEnabled(true, true);
  FocusOmniboxAndWaitForInstantOverlaySupport();

  // Add "query" to history.
  ASSERT_TRUE(AddSearchToHistory(ASCIIToUTF16("query"), 10000));
  BlockUntilHistoryProcessesPendingRequests();

  SetOmniboxText("quer");

  // Should get 2 suggestions from SearchProvider:
  //   - SWYT for "quer"
  //   - Search history suggestion for "query"
  EXPECT_EQ(2, CountSearchProviderSuggestions());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, SearchProviderRunsForFallback) {
  // Use an Instant URL that won't support Instant.
  GURL instant_url = test_server()->GetURL("files/empty.html?strk=1");
  InstantTestBase::Init(instant_url);
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlaySupport();
  // Should fallback to the local overlay.
  ASSERT_NE(static_cast<InstantOverlay*>(NULL), instant()->overlay());
  EXPECT_TRUE(instant()->overlay()->IsLocal());

  // Add "query" to history and wait for Instant support.
  ASSERT_TRUE(AddSearchToHistory(ASCIIToUTF16("query"), 10000));
  BlockUntilHistoryProcessesPendingRequests();

  SetOmniboxText("quer");

  // Should get 2 suggestions from SearchProvider:
  //   - SWYT for "quer"
  //   - Search history suggestion for "query"
  EXPECT_EQ(2, CountSearchProviderSuggestions());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, SearchProviderForLocalNTP) {
  // Force local-only Instant.
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  instant()->SetInstantEnabled(true, true);

  // Add "google" to history.
  ASSERT_TRUE(AddSearchToHistory(ASCIIToUTF16("google"), 10000));
  BlockUntilHistoryProcessesPendingRequests();

  // Create an observer to wait for the autocomplete.
  content::WindowedNotificationObserver autocomplete_observer(
      chrome::NOTIFICATION_INSTANT_SENT_AUTOCOMPLETE_RESULTS,
      content::NotificationService::AllSources());

  SetOmniboxText("http://www.example.com");

  autocomplete_observer.Wait();
  ASSERT_TRUE(omnibox()->model()->autocomplete_controller()->
              search_provider()->IsNonInstantSearchDone());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OverlaySendsSearchWhatYouTyped) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // This input could be interpreted either as an URL or a query based on the
  // relative ranking of search-what-you-typed or url-what-you-typed.
  content::WindowedNotificationObserver autocomplete_observer(
      chrome::NOTIFICATION_INSTANT_SENT_AUTOCOMPLETE_RESULTS,
      content::NotificationService::AllSources());
  SetOmniboxText("define:foo");
  autocomplete_observer.Wait();

  // In this case, we should treat [define:foo] as a query, so
  // search-what-you-typed should be the top suggestion.
  EXPECT_TRUE(ExecuteScript(
      "var sorted = chrome.embeddedSearch.searchBox.nativeSuggestions.sort("
          "function (a,b) {"
            "return b.rankingData.relevance - a.rankingData.relevance;"
          "});"));
  std::string type;
  EXPECT_TRUE(GetStringFromJS(instant()->GetOverlayContents(),
                              "sorted[0].type", &type));
  ASSERT_EQ("search-what-you-typed", type);
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       OverlayDoesNotEchoSearchProviderNAVSUGGEST) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Show the overlay so suggestions are allowed.
  SetOmniboxTextAndWaitForOverlayToShow("www.");
  content::WebContents* overlay = instant()->GetOverlayContents();

  // Set a URL suggestion and wait for SearchProvider to echo it.
  content::WindowedNotificationObserver autocomplete_observer(
      chrome::NOTIFICATION_INSTANT_SENT_AUTOCOMPLETE_RESULTS,
      content::NotificationService::AllSources());
  instant()->SetSuggestions(
      overlay,
      std::vector<InstantSuggestion>(
          1,
          InstantSuggestion(ASCIIToUTF16("http://www.example.com/"),
                            INSTANT_COMPLETE_NOW,
                            INSTANT_SUGGESTION_URL,
                            ASCIIToUTF16("www."),
                            kNoMatchIndex)));
  autocomplete_observer.Wait();

  // Check that SearchProvider set a NAVSUGGEST match.
  bool have_navsuggest_match = false;
  SearchProvider* search_provider =
      omnibox()->model()->autocomplete_controller()->search_provider();
  for (ACMatches::const_iterator match = search_provider->matches().begin();
       match != search_provider->matches().end(); ++match) {
    if (match->type == AutocompleteMatchType::NAVSUGGEST) {
      have_navsuggest_match = true;
      break;
    }
  }
  ASSERT_TRUE(have_navsuggest_match);

  // Check that InstantController did not send the NAVSUGGEST match.
  bool sent_navsuggest_match = true;
  EXPECT_TRUE(GetBoolFromJS(overlay,
      "chrome.embeddedSearch.searchBox.nativeSuggestions.some("
          "function (s) {"
            "return s.type == 'navsuggest';"
          "})", &sent_navsuggest_match));
  EXPECT_FALSE(sent_navsuggest_match);
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, AcceptingURLSearchDoesNotNavigate) {
  // Get a committed Instant tab, which will be in the Instant process and thus
  // support chrome::GetSearchTerms().
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlaySupport();

  // Create an observer to wait for the instant tab to support Instant.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
      content::NotificationService::AllSources());

  // Do a search and commit it.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("foo"));
  EXPECT_EQ(ASCIIToUTF16("foo"), omnibox()->GetText());
  browser()->window()->GetLocationBar()->AcceptInput();
  observer.Wait();

  // Set URL-like search terms for the instant tab.
  content::WebContents* instant_tab = instant()->instant_tab()->contents();
  content::NavigationEntry* visible_entry =
      instant_tab->GetController().GetVisibleEntry();
  visible_entry->SetExtraData(sessions::kSearchTermsKey,
                              ASCIIToUTF16("http://example.com"));
  SetOmniboxText("http://example.com");
  omnibox()->model()->SetInputInProgress(false);
  omnibox()->CloseOmniboxPopup();

  // Accept the omnibox input.
  EXPECT_FALSE(omnibox()->model()->user_input_in_progress());
  EXPECT_EQ(ToolbarModel::URL_LIKE_SEARCH_TERMS,
            browser()->toolbar_model()->GetSearchTermsType());
  GURL instant_tab_url = instant_tab->GetURL();
  browser()->window()->GetLocationBar()->AcceptInput();
  EXPECT_EQ(instant_tab_url, instant_tab->GetURL());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, AcceptingJSSearchDoesNotRunJS) {
  // Get a committed Instant tab, which will be in the Instant process and thus
  // support chrome::GetSearchTerms().
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlaySupport();

  // Create an observer to wait for the instant tab to support Instant.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
      content::NotificationService::AllSources());

  // Do a search and commit it.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("foo"));
  EXPECT_EQ(ASCIIToUTF16("foo"), omnibox()->GetText());
  browser()->window()->GetLocationBar()->AcceptInput();
  observer.Wait();

  // Set URL-like search terms for the instant tab.
  content::WebContents* instant_tab = instant()->instant_tab()->contents();
  content::NavigationEntry* visible_entry =
      instant_tab->GetController().GetVisibleEntry();
  const char kEvilJS[] = "javascript:document.title='evil';1;";
  visible_entry->SetExtraData(sessions::kSearchTermsKey, ASCIIToUTF16(kEvilJS));
  SetOmniboxText(kEvilJS);
  omnibox()->model()->SetInputInProgress(false);
  omnibox()->CloseOmniboxPopup();

  // Accept the omnibox input.
  EXPECT_FALSE(omnibox()->model()->user_input_in_progress());
  EXPECT_EQ(ToolbarModel::URL_LIKE_SEARCH_TERMS,
            browser()->toolbar_model()->GetSearchTermsType());
  browser()->window()->GetLocationBar()->AcceptInput();
  // Force some Javascript to run in the renderer so the inline javascript:
  // would be forced to run if it's going to.
  EXPECT_TRUE(content::ExecuteScript(instant_tab, "1;"));
  EXPECT_NE(ASCIIToUTF16("evil"), instant_tab->GetTitle());
}

// Flaky on mac: http://crbug.com/242164
#if defined(OS_MACOSX)
#define MAYBE_ReloadSearchAfterBackReloadsCorrectQuery DISABLED_ReloadSearchAfterBackReloadsCorrectQuery
#else
#define MAYBE_ReloadSearchAfterBackReloadsCorrectQuery ReloadSearchAfterBackReloadsCorrectQuery
#endif

IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       MAYBE_ReloadSearchAfterBackReloadsCorrectQuery) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlaySupport();

  // Create an observer to wait for the instant tab to support Instant.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
      content::NotificationService::AllSources());

  // Search for [foo].
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("foo"));
  EXPECT_EQ(ASCIIToUTF16("foo"), omnibox()->GetText());
  browser()->window()->GetLocationBar()->AcceptInput();
  observer.Wait();

  // Search again for [bar].
  content::WebContents* instant_tab = instant()->instant_tab()->contents();
  EXPECT_TRUE(content::ExecuteScript(instant_tab,
                                     "suggestion = 'bart';"));
  SetOmniboxTextAndWaitForSuggestion("bar");
  EXPECT_EQ(ASCIIToUTF16("t"), GetGrayText());

  // Accept the new query and wait for the page to navigate.
  content::WindowedNotificationObserver nav_observer(
        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
        content::NotificationService::AllSources());
  browser()->window()->GetLocationBar()->AcceptInput();
  nav_observer.Wait();

  // Press back button and reload.
  content::WindowedNotificationObserver back_observer(
        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
        content::NotificationService::AllSources());
  instant_tab->GetController().GoBack();
  back_observer.Wait();
  EXPECT_EQ("foo", GetOmniboxText());
  FocusOmnibox();
  content::WindowedNotificationObserver reload_observer(
        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
        content::NotificationService::AllSources());
  browser()->window()->GetLocationBar()->AcceptInput();
  reload_observer.Wait();

  EXPECT_EQ("foo", GetOmniboxText());
}

class InstantExtendedFirstTabTest : public InProcessBrowserTest,
                                    public InstantTestBase {
 public:
  InstantExtendedFirstTabTest() {}
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    command_line->AppendSwitch(switches::kEnableInstantExtendedAPI);
    command_line->AppendSwitch(switches::kDisableLocalFirstLoadNTP);
  }
};

// Flaky: http://crbug.com/238863
IN_PROC_BROWSER_TEST_F(
    InstantExtendedFirstTabTest, DISABLED_RedirectToLocalOnLoadFailure) {
  // Create a new window to test the first NTP load.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_WINDOW,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_BROWSER);

  const BrowserList* native_browser_list = BrowserList::GetInstance(
      chrome::HOST_DESKTOP_TYPE_NATIVE);
  ASSERT_EQ(2u, native_browser_list->size());
  set_browser(native_browser_list->get(1));

  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Also make sure our instant_tab_ is loaded.
  if (!instant()->instant_tab_) {
    content::WindowedNotificationObserver instant_tab_observer(
        chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
        content::NotificationService::AllSources());
    instant_tab_observer.Wait();
  }

  // NTP contents should be preloaded.
  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
  EXPECT_TRUE(instant()->ntp()->IsLocal());

  // Overlay contents should be preloaded.
  ASSERT_NE(static_cast<InstantOverlay*>(NULL), instant()->overlay());
  EXPECT_TRUE(instant()->overlay()->IsLocal());

  // Instant tab contents should be preloaded.
  ASSERT_NE(static_cast<InstantTab*>(NULL), instant()->instant_tab());
  EXPECT_TRUE(instant()->instant_tab()->IsLocal());
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
                       PageVisibilityEventOnCommit) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Set the text, and wait for suggestions to show up.
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("search"));

  content::WebContents* overlay = instant()->GetOverlayContents();

  // Before commiting, verify visibility calls.
  int on_visibility_calls = -1;
  EXPECT_TRUE(GetIntFromJS(overlay, "onvisibilitycalls", &on_visibility_calls));
  EXPECT_EQ(1, on_visibility_calls);

  // Commit the search by pressing Enter.
  browser()->window()->GetLocationBar()->AcceptInput();

  // After commiting, verify visibility calls.
  on_visibility_calls = -1;
  EXPECT_TRUE(GetIntFromJS(overlay, "onvisibilitycalls", &on_visibility_calls));
  EXPECT_EQ(1, on_visibility_calls);
}

// Test that if the LogDropdownShown() call records a histogram value.
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, LogDropdownShown) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
  int64 histogramValue = GetHistogramCount("Instant.TimeToFirstShowFromWeb");
  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("a"));
  EXPECT_EQ(histogramValue + 1,
            GetHistogramCount("Instant.TimeToFirstShowFromWeb"));
}

IN_PROC_BROWSER_TEST_F(InstantExtendedTest, TaskManagerPrefix) {
  TaskManagerModel* task_manager = TaskManager::GetInstance()->model();
  task_manager->StartUpdating();

  // There should be three renderers, the second being the Instant overlay,
  // and the third being the preloaded NTP.
  TaskManagerBrowserTestUtil::WaitForWebResourceChange(3);

  string16 prefix = l10n_util::GetStringFUTF16(
      IDS_TASK_MANAGER_INSTANT_OVERLAY_PREFIX, string16());

  int instant_overlays = 0;
  for (int i = 0; i < task_manager->ResourceCount(); ++i) {
    string16 title = task_manager->GetResourceTitle(i);
    if (StartsWith(title, prefix, true))
      ++instant_overlays;
  }
  EXPECT_EQ(2, instant_overlays);
}

// Broken on mac: http://crbug.com/247448
#if defined(OS_MACOSX)
#define MAYBE_KeyboardTogglesVoiceSearch DISABLED_KeyboardTogglesVoiceSearch
#else
#define MAYBE_KeyboardTogglesVoiceSearch KeyboardTogglesVoiceSearch
#endif
IN_PROC_BROWSER_TEST_F(InstantExtendedTest, MAYBE_KeyboardTogglesVoiceSearch) {
  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();

  // Test that toggle is not fired when no tab is open.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_OEM_PERIOD,
                                              true, true, false, false));
  EXPECT_TRUE(UpdateSearchState(instant()->GetOverlayContents()));
  EXPECT_EQ(0, on_toggle_voice_search_calls_);

  // Open new tab and test that toggle is fired.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(),
      GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_OEM_PERIOD,
                                              true, true, false, false));
  EXPECT_TRUE(UpdateSearchState(instant()->instant_tab()->contents()));
  EXPECT_EQ(1, on_toggle_voice_search_calls_);
}

#endif  // HTML_INSTANT_EXTENDED_POPUP