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
|
// Copyright (c) 2012 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 "chrome/browser/ui/browser_init.h"
#include <algorithm> // For max().
#include <set>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "base/environment.h"
#include "base/event_recorder.h"
#include "base/file_path.h"
#include "base/lazy_instance.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_split.h"
#include "base/threading/thread_restrictions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/auto_launch_trial.h"
#include "chrome/browser/automation/automation_provider.h"
#include "chrome/browser/automation/automation_provider_list.h"
#include "chrome/browser/automation/chrome_frame_automation_provider.h"
#include "chrome/browser/automation/testing_automation_provider.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/component_updater/component_updater_service.h"
#include "chrome/browser/component_updater/flash_component_installer.h"
#include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
#include "chrome/browser/component_updater/recovery_component_installer.h"
#include "chrome/browser/component_updater/swiftshader_component_installer.h"
#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/extensions/extension_creator.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/pack_extension_job.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/net/crl_set_fetcher.h"
#include "chrome/browser/net/predictor.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/prefs/incognito_mode_prefs.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
#include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
#include "chrome/browser/printing/print_dialog_cloud.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_io_data.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/protector/base_setting_change.h"
#include "chrome/browser/protector/protected_prefs_watcher.h"
#include "chrome/browser/protector/protector_service.h"
#include "chrome/browser/protector/protector_service_factory.h"
#include "chrome/browser/protector/protector_utils.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/sessions/session_restore.h"
#include "chrome/browser/sessions/session_service.h"
#include "chrome/browser/sessions/session_service_factory.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/browser/tab_contents/link_infobar_delegate.h"
#include "chrome/browser/tab_contents/simple_alert_infobar_delegate.h"
#include "chrome/browser/tabs/pinned_tab_codec.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/webui/ntp/app_launcher_handler.h"
#include "chrome/browser/ui/webui/sync_promo/sync_promo_trial.h"
#include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/installer/util/browser_distribution.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "grit/theme_resources_standard.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#include "chrome/browser/ui/cocoa/keystone_infobar_delegate.h"
#endif
#if defined(TOOLKIT_GTK)
#include "chrome/browser/ui/gtk/gtk_util.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/customization_document.h"
#include "chrome/browser/chromeos/enterprise_extension_observer.h"
#include "chrome/browser/chromeos/gview_request_interceptor.h"
#include "chrome/browser/chromeos/network_message_observer.h"
#include "chrome/browser/chromeos/power/low_battery_observer.h"
#include "chrome/browser/chromeos/sms_observer.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#endif
#if defined(TOOLKIT_VIEWS) && defined(OS_LINUX)
#include "ui/base/touch/touch_factory.h"
#endif
#if defined(OS_WIN)
#include "base/win/metro.h"
#include "base/win/windows_version.h"
#include "chrome/installer/util/auto_launch_util.h"
#endif
using content::BrowserThread;
using content::ChildProcessSecurityPolicy;
using content::OpenURLParams;
using content::Referrer;
using content::WebContents;
using protector::BaseSettingChange;
using protector::ProtectedPrefsWatcher;
using protector::ProtectorService;
using protector::ProtectorServiceFactory;
namespace {
static const int kMaxInfobarShown = 5;
bool in_synchronous_profile_launch = false;
#if defined(OS_WIN)
// The delegate for the infobar shown when Chrome was auto-launched.
class AutolaunchInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
AutolaunchInfoBarDelegate(InfoBarTabHelper* infobar_helper,
PrefService* prefs,
Profile* profile);
virtual ~AutolaunchInfoBarDelegate();
private:
void AllowExpiry() { should_expire_ = true; }
// ConfirmInfoBarDelegate:
virtual bool ShouldExpire(
const content::LoadCommittedDetails& details) const OVERRIDE;
virtual gfx::Image* GetIcon() const OVERRIDE;
virtual string16 GetMessageText() const OVERRIDE;
virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE;
virtual bool Accept() OVERRIDE;
virtual bool Cancel() OVERRIDE;
// The prefs to use.
PrefService* prefs_;
// Whether the user clicked one of the buttons.
bool action_taken_;
// Whether the info-bar should be dismissed on the next navigation.
bool should_expire_;
// Weak pointer to the profile, not owned by us.
Profile* profile_;
// Used to delay the expiration of the info-bar.
base::WeakPtrFactory<AutolaunchInfoBarDelegate> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(AutolaunchInfoBarDelegate);
};
AutolaunchInfoBarDelegate::AutolaunchInfoBarDelegate(
InfoBarTabHelper* infobar_helper,
PrefService* prefs,
Profile* profile)
: ConfirmInfoBarDelegate(infobar_helper),
prefs_(prefs),
action_taken_(false),
should_expire_(false),
profile_(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
auto_launch_trial::UpdateInfobarShownMetric();
int count = prefs_->GetInteger(prefs::kShownAutoLaunchInfobar);
prefs_->SetInteger(prefs::kShownAutoLaunchInfobar, count + 1);
// We want the info-bar to stick-around for a few seconds and then be hidden
// on the next navigation after that.
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&AutolaunchInfoBarDelegate::AllowExpiry,
weak_factory_.GetWeakPtr()),
base::TimeDelta::FromSeconds(8));
}
AutolaunchInfoBarDelegate::~AutolaunchInfoBarDelegate() {
if (!action_taken_) {
auto_launch_trial::UpdateInfobarResponseMetric(
auto_launch_trial::INFOBAR_IGNORE);
}
}
bool AutolaunchInfoBarDelegate::ShouldExpire(
const content::LoadCommittedDetails& details) const {
return details.is_navigation_to_different_page() && should_expire_;
}
gfx::Image* AutolaunchInfoBarDelegate::GetIcon() const {
return &ResourceBundle::GetSharedInstance().GetNativeImageNamed(
IDR_PRODUCT_LOGO_32);
}
string16 AutolaunchInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringUTF16(IDS_AUTO_LAUNCH_INFOBAR_TEXT);
}
string16 AutolaunchInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_AUTO_LAUNCH_OK : IDS_AUTO_LAUNCH_REVERT);
}
bool AutolaunchInfoBarDelegate::Accept() {
action_taken_ = true;
auto_launch_trial::UpdateInfobarResponseMetric(
auto_launch_trial::INFOBAR_OK);
return true;
}
bool AutolaunchInfoBarDelegate::Cancel() {
action_taken_ = true;
// Track infobar reponse.
auto_launch_trial::UpdateInfobarResponseMetric(
auto_launch_trial::INFOBAR_CUT_IT_OUT);
// Also make sure we keep track of how many disable and how many enable.
auto_launch_trial::UpdateToggleAutoLaunchMetric(false);
content::BrowserThread::PostTask(
content::BrowserThread::FILE, FROM_HERE,
base::Bind(&auto_launch_util::DisableForegroundStartAtLogin,
profile_->GetPath().BaseName().value()));
return true;
}
// Metro driver export, this is how metro passes the initial navigated url
// back to us.
extern "C" {
typedef const wchar_t* (*GetInitialUrl)();
}
#endif // OS_WIN
// DefaultBrowserInfoBarDelegate ----------------------------------------------
// The delegate for the infobar shown when Chrome is not the default browser.
class DefaultBrowserInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
explicit DefaultBrowserInfoBarDelegate(InfoBarTabHelper* infobar_helper,
PrefService* prefs);
private:
virtual ~DefaultBrowserInfoBarDelegate();
void AllowExpiry() { should_expire_ = true; }
// ConfirmInfoBarDelegate:
virtual bool ShouldExpire(
const content::LoadCommittedDetails& details) const OVERRIDE;
virtual gfx::Image* GetIcon() const OVERRIDE;
virtual string16 GetMessageText() const OVERRIDE;
virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE;
virtual bool NeedElevation(InfoBarButton button) const OVERRIDE;
virtual bool Accept() OVERRIDE;
virtual bool Cancel() OVERRIDE;
// The prefs to use.
PrefService* prefs_;
// Whether the user clicked one of the buttons.
bool action_taken_;
// Whether the info-bar should be dismissed on the next navigation.
bool should_expire_;
// Used to delay the expiration of the info-bar.
base::WeakPtrFactory<DefaultBrowserInfoBarDelegate> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(DefaultBrowserInfoBarDelegate);
};
DefaultBrowserInfoBarDelegate::DefaultBrowserInfoBarDelegate(
InfoBarTabHelper* infobar_helper,
PrefService* prefs)
: ConfirmInfoBarDelegate(infobar_helper),
prefs_(prefs),
action_taken_(false),
should_expire_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
// We want the info-bar to stick-around for few seconds and then be hidden
// on the next navigation after that.
MessageLoop::current()->PostDelayedTask(
FROM_HERE, base::Bind(&DefaultBrowserInfoBarDelegate::AllowExpiry,
weak_factory_.GetWeakPtr()),
base::TimeDelta::FromSeconds(8));
}
DefaultBrowserInfoBarDelegate::~DefaultBrowserInfoBarDelegate() {
if (!action_taken_)
UMA_HISTOGRAM_COUNTS("DefaultBrowserWarning.Ignored", 1);
}
bool DefaultBrowserInfoBarDelegate::ShouldExpire(
const content::LoadCommittedDetails& details) const {
return details.is_navigation_to_different_page() && should_expire_;
}
gfx::Image* DefaultBrowserInfoBarDelegate::GetIcon() const {
return &ResourceBundle::GetSharedInstance().GetNativeImageNamed(
IDR_PRODUCT_LOGO_32);
}
string16 DefaultBrowserInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringUTF16(IDS_DEFAULT_BROWSER_INFOBAR_SHORT_TEXT);
}
string16 DefaultBrowserInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_SET_AS_DEFAULT_INFOBAR_BUTTON_LABEL :
IDS_DONT_ASK_AGAIN_INFOBAR_BUTTON_LABEL);
}
bool DefaultBrowserInfoBarDelegate::NeedElevation(InfoBarButton button) const {
return button == BUTTON_OK;
}
bool DefaultBrowserInfoBarDelegate::Accept() {
action_taken_ = true;
UMA_HISTOGRAM_COUNTS("DefaultBrowserWarning.SetAsDefault", 1);
BrowserThread::PostTask(
BrowserThread::FILE,
FROM_HERE,
base::Bind(base::IgnoreResult(&ShellIntegration::SetAsDefaultBrowser)));
return true;
}
bool DefaultBrowserInfoBarDelegate::Cancel() {
action_taken_ = true;
UMA_HISTOGRAM_COUNTS("DefaultBrowserWarning.DontSetAsDefault", 1);
// User clicked "Don't ask me again", remember that.
prefs_->SetBoolean(prefs::kCheckDefaultBrowser, false);
return true;
}
#if defined(OS_WIN)
void CheckAutoLaunchCallback(Profile* profile) {
if (!auto_launch_trial::IsInAutoLaunchGroup())
return;
// We must not use GetLastActive here because this is at Chrome startup and
// no window might have been made active yet. We'll settle for any window.
Browser* browser = BrowserList::FindAnyBrowser(profile, true);
TabContentsWrapper* tab = browser->GetSelectedTabContentsWrapper();
// Don't show the info-bar if there are already info-bars showing.
InfoBarTabHelper* infobar_helper = tab->infobar_tab_helper();
if (infobar_helper->infobar_count() > 0)
return;
infobar_helper->AddInfoBar(
new AutolaunchInfoBarDelegate(infobar_helper,
tab->profile()->GetPrefs(), tab->profile()));
}
#endif
void NotifyNotDefaultBrowserCallback() {
Browser* browser = BrowserList::GetLastActive();
if (!browser)
return; // Reached during ui tests.
// In ChromeBot tests, there might be a race. This line appears to get
// called during shutdown and |tab| can be NULL.
TabContentsWrapper* tab = browser->GetSelectedTabContentsWrapper();
if (!tab)
return;
// Don't show the info-bar if there are already info-bars showing.
InfoBarTabHelper* infobar_helper = tab->infobar_tab_helper();
if (infobar_helper->infobar_count() > 0)
return;
infobar_helper->AddInfoBar(
new DefaultBrowserInfoBarDelegate(infobar_helper,
tab->profile()->GetPrefs()));
}
void CheckDefaultBrowserCallback() {
if (ShellIntegration::IsDefaultBrowser() ||
!ShellIntegration::CanSetAsDefaultBrowser()) {
return;
}
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&NotifyNotDefaultBrowserCallback));
}
// SessionCrashedInfoBarDelegate ----------------------------------------------
// A delegate for the InfoBar shown when the previous session has crashed.
class SessionCrashedInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
SessionCrashedInfoBarDelegate(Profile* profile,
InfoBarTabHelper* infobar_helper);
private:
virtual ~SessionCrashedInfoBarDelegate();
// ConfirmInfoBarDelegate:
virtual gfx::Image* GetIcon() const OVERRIDE;
virtual string16 GetMessageText() const OVERRIDE;
virtual int GetButtons() const OVERRIDE;
virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE;
virtual bool Accept() OVERRIDE;
// The Profile that we restore sessions from.
Profile* profile_;
DISALLOW_COPY_AND_ASSIGN(SessionCrashedInfoBarDelegate);
};
SessionCrashedInfoBarDelegate::SessionCrashedInfoBarDelegate(
Profile* profile,
InfoBarTabHelper* infobar_helper)
: ConfirmInfoBarDelegate(infobar_helper),
profile_(profile) {
}
SessionCrashedInfoBarDelegate::~SessionCrashedInfoBarDelegate() {
}
gfx::Image* SessionCrashedInfoBarDelegate::GetIcon() const {
return &ResourceBundle::GetSharedInstance().GetNativeImageNamed(
IDR_INFOBAR_RESTORE_SESSION);
}
string16 SessionCrashedInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringUTF16(IDS_SESSION_CRASHED_VIEW_MESSAGE);
}
int SessionCrashedInfoBarDelegate::GetButtons() const {
return BUTTON_OK;
}
string16 SessionCrashedInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
DCHECK_EQ(BUTTON_OK, button);
return l10n_util::GetStringUTF16(IDS_SESSION_CRASHED_VIEW_RESTORE_BUTTON);
}
bool SessionCrashedInfoBarDelegate::Accept() {
uint32 behavior = 0;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (browser && browser->tab_count() == 1
&& browser->GetWebContentsAt(0)->GetURL() ==
GURL(chrome::kChromeUINewTabURL)) {
// There is only one tab and its the new tab page, make session restore
// clobber it.
behavior = SessionRestore::CLOBBER_CURRENT_TAB;
}
SessionRestore::RestoreSession(
profile_, browser, behavior, std::vector<GURL>());
return true;
}
// Utility functions ----------------------------------------------------------
enum LaunchMode {
LM_TO_BE_DECIDED = 0, // Possibly direct launch or via a shortcut.
LM_AS_WEBAPP, // Launched as a installed web application.
LM_WITH_URLS, // Launched with urls in the cmd line.
LM_SHORTCUT_NONE, // Not launched from a shortcut.
LM_SHORTCUT_NONAME, // Launched from shortcut but no name available.
LM_SHORTCUT_UNKNOWN, // Launched from user-defined shortcut.
LM_SHORTCUT_QUICKLAUNCH, // Launched from the quick launch bar.
LM_SHORTCUT_DESKTOP, // Launched from a desktop shortcut.
LM_SHORTCUT_TASKBAR, // Launched from the taskbar.
LM_LINUX_MAC_BEOS // Other OS buckets start here.
};
#if defined(OS_WIN)
// Undocumented flag in the startup info structure tells us what shortcut was
// used to launch the browser. See http://www.catch22.net/tuts/undoc01 for
// more information. Confirmed to work on XP, Vista and Win7.
LaunchMode GetLaunchShortcutKind() {
STARTUPINFOW si = { sizeof(si) };
GetStartupInfoW(&si);
if (si.dwFlags & 0x800) {
if (!si.lpTitle)
return LM_SHORTCUT_NONAME;
string16 shortcut(si.lpTitle);
// The windows quick launch path is not localized.
if (shortcut.find(L"\\Quick Launch\\") != string16::npos) {
if (base::win::GetVersion() >= base::win::VERSION_WIN7)
return LM_SHORTCUT_TASKBAR;
else
return LM_SHORTCUT_QUICKLAUNCH;
}
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string appdata_path;
env->GetVar("USERPROFILE", &appdata_path);
if (!appdata_path.empty() &&
shortcut.find(ASCIIToWide(appdata_path)) != std::wstring::npos)
return LM_SHORTCUT_DESKTOP;
return LM_SHORTCUT_UNKNOWN;
}
return LM_SHORTCUT_NONE;
}
#else
// TODO(cpu): Port to other platforms.
LaunchMode GetLaunchShortcutKind() {
return LM_LINUX_MAC_BEOS;
}
#endif
// Log in a histogram the frequency of launching by the different methods. See
// LaunchMode enum for the actual values of the buckets.
void RecordLaunchModeHistogram(LaunchMode mode) {
int bucket = (mode == LM_TO_BE_DECIDED) ? GetLaunchShortcutKind() : mode;
UMA_HISTOGRAM_COUNTS_100("Launch.Modes", bucket);
}
GURL GetWelcomePageURL() {
std::string welcome_url = l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL);
return GURL(welcome_url);
}
void UrlsToTabs(const std::vector<GURL>& urls,
std::vector<BrowserInit::LaunchWithProfile::Tab>* tabs) {
for (size_t i = 0; i < urls.size(); ++i) {
BrowserInit::LaunchWithProfile::Tab tab;
tab.is_pinned = false;
tab.url = urls[i];
tabs->push_back(tab);
}
}
// Return true if the command line option --app-id is used. Set
// |out_extension| to the app to open, and |out_launch_container|
// to the type of window into which the app should be open.
bool GetAppLaunchContainer(
Profile* profile,
const std::string& app_id,
const Extension** out_extension,
extension_misc::LaunchContainer* out_launch_container) {
ExtensionService* extensions_service = profile->GetExtensionService();
const Extension* extension =
extensions_service->GetExtensionById(app_id, false);
// The extension with id |app_id| may have been uninstalled.
if (!extension)
return false;
// Look at preferences to find the right launch container. If no
// preference is set, launch as a window.
extension_misc::LaunchContainer launch_container =
extensions_service->extension_prefs()->GetLaunchContainer(
extension, ExtensionPrefs::LAUNCH_WINDOW);
*out_extension = extension;
*out_launch_container = launch_container;
return true;
}
void RecordCmdLineAppHistogram() {
AppLauncherHandler::RecordAppLaunchType(
extension_misc::APP_LAUNCH_CMD_LINE_APP);
}
void RecordAppLaunches(
Profile* profile,
const std::vector<GURL>& cmd_line_urls,
const std::vector<BrowserInit::LaunchWithProfile::Tab>& autolaunch_tabs) {
ExtensionService* extension_service = profile->GetExtensionService();
DCHECK(extension_service);
for (size_t i = 0; i < cmd_line_urls.size(); ++i) {
if (extension_service->IsInstalledApp(cmd_line_urls.at(i))) {
AppLauncherHandler::RecordAppLaunchType(
extension_misc::APP_LAUNCH_CMD_LINE_URL);
}
}
for (size_t i = 0; i < autolaunch_tabs.size(); ++i) {
if (extension_service->IsInstalledApp(autolaunch_tabs.at(i).url)) {
AppLauncherHandler::RecordAppLaunchType(
extension_misc::APP_LAUNCH_AUTOLAUNCH);
}
}
}
void RegisterComponentsForUpdate(const CommandLine& command_line) {
ComponentUpdateService* cus = g_browser_process->component_updater();
if (!cus)
return;
// Registration can be before of after cus->Start() so it is ok to post
// a task to the UI thread to do registration once you done the necessary
// file IO to know you existing component version.
RegisterRecoveryComponent(cus, g_browser_process->local_state());
RegisterPepperFlashComponent(cus);
RegisterNPAPIFlashComponent(cus);
RegisterSwiftShaderComponent(cus);
// CRLSetFetcher attempts to load a CRL set from either the local disk or
// network.
if (!command_line.HasSwitch(switches::kDisableCRLSets))
g_browser_process->crl_set_fetcher()->StartInitialLoad(cus);
// This developer version of Pnacl should only be installed for developers.
if (command_line.HasSwitch(switches::kEnablePnacl)) {
RegisterPnaclComponent(cus);
}
cus->Start();
}
// Keeps track on which profiles have been launched.
class ProfileLaunchObserver : public content::NotificationObserver {
public:
ProfileLaunchObserver() {
registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
content::NotificationService::AllSources());
}
virtual ~ProfileLaunchObserver() {}
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) OVERRIDE {
switch (type) {
case chrome::NOTIFICATION_PROFILE_DESTROYED: {
Profile* profile = content::Source<Profile>(source).ptr();
launched_profiles.erase(profile);
break;
}
default:
NOTREACHED();
}
}
bool HasBeenLaunched(const Profile* profile) {
return launched_profiles.find(profile) != launched_profiles.end();
}
void AddLaunched(const Profile* profile) {
launched_profiles.insert(profile);
}
private:
std::set<const Profile*> launched_profiles;
content::NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(ProfileLaunchObserver);
};
base::LazyInstance<ProfileLaunchObserver> profile_launch_observer =
LAZY_INSTANCE_INITIALIZER;
// Returns true if |profile| has exited uncleanly and has not been launched
// after the unclean exit.
bool HasPendingUncleanExit(Profile* profile) {
return !profile->DidLastSessionExitCleanly() &&
!profile_launch_observer.Get().HasBeenLaunched(profile);
}
} // namespace
// BrowserInit ----------------------------------------------------------------
BrowserInit::BrowserInit() {}
BrowserInit::~BrowserInit() {}
// static
bool BrowserInit::was_restarted_read_ = false;
void BrowserInit::AddFirstRunTab(const GURL& url) {
first_run_tabs_.push_back(url);
}
// static
bool BrowserInit::InSynchronousProfileLaunch() {
return in_synchronous_profile_launch;
}
// static
void BrowserInit::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterIntegerPref(
prefs::kShownAutoLaunchInfobar, 0, PrefService::UNSYNCABLE_PREF);
}
bool BrowserInit::LaunchBrowser(const CommandLine& command_line,
Profile* profile,
const FilePath& cur_dir,
IsProcessStartup process_startup,
IsFirstRun is_first_run,
int* return_code) {
in_synchronous_profile_launch = process_startup == IS_PROCESS_STARTUP;
DCHECK(profile);
// Continue with the incognito profile from here on if Incognito mode
// is forced.
if (IncognitoModePrefs::ShouldLaunchIncognito(command_line,
profile->GetPrefs())) {
profile = profile->GetOffTheRecordProfile();
} else if (command_line.HasSwitch(switches::kIncognito)) {
LOG(WARNING) << "Incognito mode disabled by policy, launching a normal "
<< "browser session.";
}
BrowserInit::LaunchWithProfile lwp(cur_dir, command_line, this, is_first_run);
std::vector<GURL> urls_to_launch = BrowserInit::GetURLsFromCommandLine(
command_line, cur_dir, profile);
bool launched = lwp.Launch(profile, urls_to_launch,
in_synchronous_profile_launch);
in_synchronous_profile_launch = false;
if (!launched) {
LOG(ERROR) << "launch error";
if (return_code)
*return_code = chrome::RESULT_CODE_INVALID_CMDLINE_URL;
return false;
}
profile_launch_observer.Get().AddLaunched(profile);
#if defined(OS_CHROMEOS)
// Initialize Chrome OS preferences like touch pad sensitivity. For the
// preferences to work in the guest mode, the initialization has to be
// done after |profile| is switched to the incognito profile (which
// is actually GuestSessionProfile in the guest mode). See the
// GetOffTheRecordProfile() call above.
profile->InitChromeOSPreferences();
if (process_startup) {
// This observer is a singleton. It is never deleted but the pointer is kept
// in a static so that it isn't reported as a leak.
static chromeos::LowBatteryObserver* low_battery_observer =
new chromeos::LowBatteryObserver(profile);
chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(
low_battery_observer);
static chromeos::NetworkMessageObserver* network_message_observer =
new chromeos::NetworkMessageObserver(profile);
chromeos::CrosLibrary::Get()->GetNetworkLibrary()
->AddNetworkManagerObserver(network_message_observer);
chromeos::CrosLibrary::Get()->GetNetworkLibrary()
->AddCellularDataPlanObserver(network_message_observer);
chromeos::CrosLibrary::Get()->GetNetworkLibrary()
->AddUserActionObserver(network_message_observer);
static chromeos::SmsObserver* sms_observer =
new chromeos::SmsObserver(profile);
chromeos::CrosLibrary::Get()->GetNetworkLibrary()
->AddNetworkManagerObserver(sms_observer);
profile->SetupChromeOSEnterpriseExtensionObserver();
}
#endif
return true;
}
// static
bool BrowserInit::WasRestarted() {
// Stores the value of the preference kWasRestarted had when it was read.
static bool was_restarted = false;
if (!was_restarted_read_) {
PrefService* pref_service = g_browser_process->local_state();
was_restarted = pref_service->GetBoolean(prefs::kWasRestarted);
pref_service->SetBoolean(prefs::kWasRestarted, false);
was_restarted_read_ = true;
}
return was_restarted;
}
// static
SessionStartupPref BrowserInit::GetSessionStartupPref(
const CommandLine& command_line,
Profile* profile) {
SessionStartupPref pref = SessionStartupPref::GetStartupPref(profile);
// Session restore should be avoided on the first run.
if (first_run::IsChromeFirstRun())
pref.type = SessionStartupPref::DEFAULT;
if (command_line.HasSwitch(switches::kRestoreLastSession) ||
BrowserInit::WasRestarted()) {
pref.type = SessionStartupPref::LAST;
}
if (pref.type == SessionStartupPref::LAST &&
IncognitoModePrefs::ShouldLaunchIncognito(command_line,
profile->GetPrefs())) {
// We don't store session information when incognito. If the user has
// chosen to restore last session and launched incognito, fallback to
// default launch behavior.
pref.type = SessionStartupPref::DEFAULT;
}
return pref;
}
// BrowserInit::LaunchWithProfile::Tab ----------------------------------------
BrowserInit::LaunchWithProfile::Tab::Tab() : is_app(false), is_pinned(true) {}
BrowserInit::LaunchWithProfile::Tab::~Tab() {}
// BrowserInit::LaunchWithProfile ---------------------------------------------
BrowserInit::LaunchWithProfile::LaunchWithProfile(
const FilePath& cur_dir,
const CommandLine& command_line,
IsFirstRun is_first_run)
: cur_dir_(cur_dir),
command_line_(command_line),
profile_(NULL),
browser_init_(NULL),
is_first_run_(is_first_run == IS_FIRST_RUN) {
}
BrowserInit::LaunchWithProfile::LaunchWithProfile(
const FilePath& cur_dir,
const CommandLine& command_line,
BrowserInit* browser_init,
IsFirstRun is_first_run)
: cur_dir_(cur_dir),
command_line_(command_line),
profile_(NULL),
browser_init_(browser_init),
is_first_run_(is_first_run == IS_FIRST_RUN) {
}
BrowserInit::LaunchWithProfile::~LaunchWithProfile() {
}
bool BrowserInit::LaunchWithProfile::Launch(
Profile* profile,
const std::vector<GURL>& urls_to_open,
bool process_startup) {
DCHECK(profile);
profile_ = profile;
if (command_line_.HasSwitch(switches::kDnsLogDetails))
chrome_browser_net::EnablePredictorDetailedLog(true);
if (command_line_.HasSwitch(switches::kDnsPrefetchDisable) &&
profile->GetNetworkPredictor()) {
profile->GetNetworkPredictor()->EnablePredictor(false);
}
if (command_line_.HasSwitch(switches::kDumpHistogramsOnExit))
base::StatisticsRecorder::set_dump_on_exit(true);
if (command_line_.HasSwitch(switches::kRemoteDebuggingPort)) {
std::string port_str =
command_line_.GetSwitchValueASCII(switches::kRemoteDebuggingPort);
int64 port;
if (base::StringToInt64(port_str, &port) && port > 0 && port < 65535) {
std::string frontend_str;
if (command_line_.HasSwitch(switches::kRemoteDebuggingFrontend)) {
frontend_str = command_line_.GetSwitchValueASCII(
switches::kRemoteDebuggingFrontend);
}
g_browser_process->InitDevToolsHttpProtocolHandler(
profile,
"127.0.0.1",
static_cast<int>(port),
frontend_str);
} else {
DLOG(WARNING) << "Invalid http debugger port number " << port;
}
}
// Open the required browser windows and tabs. First, see if
// we're being run as an application window. If so, the user
// opened an app shortcut. Don't restore tabs or open initial
// URLs in that case. The user should see the window as an app,
// not as chrome.
if (OpenApplicationWindow(profile)) {
RecordLaunchModeHistogram(LM_AS_WEBAPP);
} else {
RecordLaunchModeHistogram(urls_to_open.empty()?
LM_TO_BE_DECIDED : LM_WITH_URLS);
// Notify user if the Preferences backup is invalid or changes to settings
// affecting browser startup have been detected.
CheckPreferencesBackup(profile);
ProcessLaunchURLs(process_startup, urls_to_open);
// If this is an app launch, but we didn't open an app window, it may
// be an app tab.
OpenApplicationTab(profile);
if (process_startup) {
if (browser_defaults::kOSSupportsOtherBrowsers &&
!command_line_.HasSwitch(switches::kNoDefaultBrowserCheck)) {
if (!CheckIfAutoLaunched(profile)) {
// Check whether we are the default browser.
CheckDefaultBrowser(profile);
}
}
#if defined(OS_MACOSX)
// Check whether the auto-update system needs to be promoted from user
// to system.
KeystoneInfoBar::PromotionInfoBar(profile);
#endif
}
}
#if defined(OS_WIN)
// Print the selected page if the command line switch exists. Note that the
// current selected tab would be the page which will be printed.
if (command_line_.HasSwitch(switches::kPrint)) {
Browser* browser = BrowserList::GetLastActive();
browser->Print();
}
#endif
// If we're recording or playing back, startup the EventRecorder now
// unless otherwise specified.
if (!command_line_.HasSwitch(switches::kNoEvents)) {
FilePath script_path;
PathService::Get(chrome::FILE_RECORDED_SCRIPT, &script_path);
bool record_mode = command_line_.HasSwitch(switches::kRecordMode);
bool playback_mode = command_line_.HasSwitch(switches::kPlaybackMode);
if (record_mode && chrome::kRecordModeEnabled)
base::EventRecorder::current()->StartRecording(script_path);
if (playback_mode)
base::EventRecorder::current()->StartPlayback(script_path);
}
#if defined(OS_WIN)
if (process_startup)
ShellIntegration::MigrateChromiumShortcuts();
#endif // defined(OS_WIN)
return true;
}
bool BrowserInit::LaunchWithProfile::IsAppLaunch(std::string* app_url,
std::string* app_id) {
if (command_line_.HasSwitch(switches::kApp)) {
if (app_url)
*app_url = command_line_.GetSwitchValueASCII(switches::kApp);
return true;
}
if (command_line_.HasSwitch(switches::kAppId)) {
if (app_id)
*app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
return true;
}
return false;
}
bool BrowserInit::LaunchWithProfile::OpenApplicationTab(Profile* profile) {
std::string app_id;
// App shortcuts to URLs always open in an app window. Because this
// function will open an app that should be in a tab, there is no need
// to look at the app URL. OpenApplicationWindow() will open app url
// shortcuts.
if (!IsAppLaunch(NULL, &app_id) || app_id.empty())
return false;
extension_misc::LaunchContainer launch_container;
const Extension* extension;
if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
return false;
// If the user doesn't want to open a tab, fail.
if (launch_container != extension_misc::LAUNCH_TAB)
return false;
RecordCmdLineAppHistogram();
WebContents* app_tab = Browser::OpenApplicationTab(profile, extension, GURL(),
NEW_FOREGROUND_TAB);
return (app_tab != NULL);
}
bool BrowserInit::LaunchWithProfile::OpenApplicationWindow(Profile* profile) {
std::string url_string, app_id;
if (!IsAppLaunch(&url_string, &app_id))
return false;
// This can fail if the app_id is invalid. It can also fail if the
// extension is external, and has not yet been installed.
// TODO(skerner): Do something reasonable here. Pop up a warning panel?
// Open an URL to the gallery page of the extension id?
if (!app_id.empty()) {
extension_misc::LaunchContainer launch_container;
const Extension* extension;
if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
return false;
// TODO(skerner): Could pass in |extension| and |launch_container|,
// and avoid calling GetAppLaunchContainer() both here and in
// OpenApplicationTab().
if (launch_container == extension_misc::LAUNCH_TAB)
return false;
RecordCmdLineAppHistogram();
WebContents* tab_in_app_window = Browser::OpenApplication(
profile, extension, launch_container, GURL(), NEW_WINDOW);
return (tab_in_app_window != NULL);
}
if (url_string.empty())
return false;
#if defined(OS_WIN) // Fix up Windows shortcuts.
ReplaceSubstringsAfterOffset(&url_string, 0, "\\x", "%");
#endif
GURL url(url_string);
// Restrict allowed URLs for --app switch.
if (!url.is_empty() && url.is_valid()) {
ChildProcessSecurityPolicy *policy =
ChildProcessSecurityPolicy::GetInstance();
if (policy->IsWebSafeScheme(url.scheme()) ||
url.SchemeIs(chrome::kFileScheme)) {
if (profile->GetExtensionService()->IsInstalledApp(url)) {
RecordCmdLineAppHistogram();
} else {
AppLauncherHandler::RecordAppLaunchType(
extension_misc::APP_LAUNCH_CMD_LINE_APP_LEGACY);
}
WebContents* app_tab = Browser::OpenAppShortcutWindow(
profile,
url,
true); // Update app info.
return (app_tab != NULL);
}
}
return false;
}
void BrowserInit::LaunchWithProfile::ProcessLaunchURLs(
bool process_startup,
const std::vector<GURL>& urls_to_open) {
// If we're starting up in "background mode" (no open browser window) then
// don't open any browser windows, unless kAutoLaunchAtStartup is also
// specified.
if (process_startup &&
command_line_.HasSwitch(switches::kNoStartupWindow) &&
!command_line_.HasSwitch(switches::kAutoLaunchAtStartup)) {
return;
}
if (process_startup && ProcessStartupURLs(urls_to_open)) {
// ProcessStartupURLs processed the urls, nothing else to do.
return;
}
IsProcessStartup is_process_startup = process_startup ?
IS_PROCESS_STARTUP : IS_NOT_PROCESS_STARTUP;
if (!process_startup) {
// Even if we're not starting a new process, this may conceptually be
// "startup" for the user and so should be handled in a similar way. Eg.,
// Chrome may have been running in the background due to an app with a
// background page being installed, or running with only an app window
// displayed.
SessionService* service = SessionServiceFactory::GetForProfile(profile_);
if (service && service->ShouldNewWindowStartSession()) {
// Restore the last session if any.
if (!HasPendingUncleanExit(profile_) &&
service->RestoreIfNecessary(urls_to_open)) {
return;
}
// Open user-specified URLs like pinned tabs and startup tabs.
Browser* browser = ProcessSpecifiedURLs(urls_to_open);
if (browser) {
AddInfoBarsIfNecessary(browser, is_process_startup);
return;
}
}
}
// Session startup didn't occur, open the urls.
Browser* browser = NULL;
std::vector<GURL> adjust_urls = urls_to_open;
if (adjust_urls.empty())
AddStartupURLs(&adjust_urls);
else if (!command_line_.HasSwitch(switches::kOpenInNewWindow))
browser = BrowserList::GetLastActiveWithProfile(profile_);
// This will launch a browser; prevent session restore.
in_synchronous_profile_launch = true;
browser = OpenURLsInBrowser(browser, process_startup, adjust_urls);
in_synchronous_profile_launch = false;
AddInfoBarsIfNecessary(browser, is_process_startup);
}
bool BrowserInit::LaunchWithProfile::ProcessStartupURLs(
const std::vector<GURL>& urls_to_open) {
SessionStartupPref pref = GetSessionStartupPref(command_line_, profile_);
if (pref.type == SessionStartupPref::LAST) {
if (!profile_->DidLastSessionExitCleanly() &&
!command_line_.HasSwitch(switches::kRestoreLastSession)) {
// The last session crashed. It's possible automatically loading the
// page will trigger another crash, locking the user out of chrome.
// To avoid this, don't restore on startup but instead show the crashed
// infobar.
return false;
}
uint32 restore_behavior = SessionRestore::SYNCHRONOUS |
SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
#if defined(OS_MACOSX)
// On Mac, when restoring a session with no windows, suppress the creation
// of a new window in the case where the system is launching Chrome via a
// login item or Lion's resume feature.
if (base::mac::WasLaunchedAsLoginOrResumeItem()) {
restore_behavior = restore_behavior &
~SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
}
#endif
Browser* browser = SessionRestore::RestoreSession(profile_,
NULL,
restore_behavior,
urls_to_open);
AddInfoBarsIfNecessary(browser, IS_PROCESS_STARTUP);
return true;
}
Browser* browser = ProcessSpecifiedURLs(urls_to_open);
if (!browser)
return false;
AddInfoBarsIfNecessary(browser, IS_PROCESS_STARTUP);
return true;
}
Browser* BrowserInit::LaunchWithProfile::ProcessSpecifiedURLs(
const std::vector<GURL>& urls_to_open) {
SessionStartupPref pref = GetSessionStartupPref(command_line_, profile_);
std::vector<Tab> tabs;
// Pinned tabs should not be displayed when chrome is launched
// in incognito mode.
if (!IncognitoModePrefs::ShouldLaunchIncognito(command_line_,
profile_->GetPrefs())) {
tabs = PinnedTabCodec::ReadPinnedTabs(profile_);
}
RecordAppLaunches(profile_, urls_to_open, tabs);
if (!urls_to_open.empty()) {
// If urls were specified on the command line, use them.
UrlsToTabs(urls_to_open, &tabs);
} else if (pref.type == SessionStartupPref::URLS && !pref.urls.empty()) {
// Only use the set of urls specified in preferences if nothing was
// specified on the command line. Filter out any urls that are to be
// restored by virtue of having been previously pinned.
AddUniqueURLs(pref.urls, &tabs);
} else if (pref.type == SessionStartupPref::DEFAULT) {
std::vector<GURL> urls;
AddStartupURLs(&urls);
UrlsToTabs(urls, &tabs);
} else if (pref.type == SessionStartupPref::HOMEPAGE) {
// If the user had 'homepage' selected, we should have migrated them to
// 'URLs' instead.
DLOG(ERROR) << "pref.type == HOMEPAGE";
NOTREACHED();
}
if (tabs.empty())
return NULL;
Browser* browser = OpenTabsInBrowser(NULL, true, tabs);
return browser;
}
void BrowserInit::LaunchWithProfile::AddUniqueURLs(
const std::vector<GURL>& urls,
std::vector<Tab>* tabs) {
size_t num_existing_tabs = tabs->size();
for (size_t i = 0; i < urls.size(); ++i) {
bool in_tabs = false;
for (size_t j = 0; j < num_existing_tabs; ++j) {
if (urls[i] == (*tabs)[j].url) {
in_tabs = true;
break;
}
}
if (!in_tabs) {
BrowserInit::LaunchWithProfile::Tab tab;
tab.is_pinned = false;
tab.url = urls[i];
tabs->push_back(tab);
}
}
}
Browser* BrowserInit::LaunchWithProfile::OpenURLsInBrowser(
Browser* browser,
bool process_startup,
const std::vector<GURL>& urls) {
std::vector<Tab> tabs;
UrlsToTabs(urls, &tabs);
return OpenTabsInBrowser(browser, process_startup, tabs);
}
Browser* BrowserInit::LaunchWithProfile::OpenTabsInBrowser(
Browser* browser,
bool process_startup,
const std::vector<Tab>& tabs) {
DCHECK(!tabs.empty());
// If we don't yet have a profile, try to use the one we're given from
// |browser|. While we may not end up actually using |browser| (since it
// could be a popup window), we can at least use the profile.
if (!profile_ && browser)
profile_ = browser->profile();
if (!browser || !browser->is_type_tabbed()) {
browser = Browser::Create(profile_);
} else {
#if defined(TOOLKIT_GTK)
// Setting the time of the last action on the window here allows us to steal
// focus, which is what the user wants when opening a new tab in an existing
// browser window.
gtk_util::SetWMLastUserActionTime(browser->window()->GetNativeHandle());
#endif
}
#if !defined(OS_MACOSX)
// In kiosk mode, we want to always be fullscreen, so switch to that now.
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode))
browser->ToggleFullscreenMode();
#endif
bool first_tab = true;
for (size_t i = 0; i < tabs.size(); ++i) {
// We skip URLs that we'd have to launch an external protocol handler for.
// This avoids us getting into an infinite loop asking ourselves to open
// a URL, should the handler be (incorrectly) configured to be us. Anyone
// asking us to open such a URL should really ask the handler directly.
bool handled_by_chrome = ProfileIOData::IsHandledURL(tabs[i].url) ||
(profile_ && profile_->GetProtocolHandlerRegistry()->IsHandledProtocol(
tabs[i].url.scheme()));
if (!process_startup && !handled_by_chrome)
continue;
int add_types = first_tab ? TabStripModel::ADD_ACTIVE :
TabStripModel::ADD_NONE;
add_types |= TabStripModel::ADD_FORCE_INDEX;
if (tabs[i].is_pinned)
add_types |= TabStripModel::ADD_PINNED;
int index = browser->GetIndexForInsertionDuringRestore(i);
browser::NavigateParams params(browser, tabs[i].url,
content::PAGE_TRANSITION_START_PAGE);
params.disposition = first_tab ? NEW_FOREGROUND_TAB :
NEW_BACKGROUND_TAB;
params.tabstrip_index = index;
params.tabstrip_add_types = add_types;
params.extension_app_id = tabs[i].app_id;
browser::Navigate(¶ms);
first_tab = false;
}
if (!browser->GetSelectedWebContents()) {
// TODO: this is a work around for 110909. Figure out why it's needed.
if (!browser->tab_count())
browser->AddBlankTab(true);
else
browser->ActivateTabAt(0, false);
}
browser->window()->Show();
// TODO(jcampan): http://crbug.com/8123 we should not need to set the initial
// focus explicitly.
browser->GetSelectedWebContents()->GetView()->SetInitialFocus();
return browser;
}
void BrowserInit::LaunchWithProfile::AddInfoBarsIfNecessary(
Browser* browser,
IsProcessStartup is_process_startup) {
if (!browser || !profile_ || browser->tab_count() == 0)
return;
TabContentsWrapper* tab_contents = browser->GetSelectedTabContentsWrapper();
AddCrashedInfoBarIfNecessary(browser, tab_contents);
// The bad flags info bar and the obsolete system info bar are only added to
// the first profile which is launched. Other profiles might be restoring the
// browsing sessions asynchronously, so we cannot add the info bars to the
// focused tabs here.
if (is_process_startup == IS_PROCESS_STARTUP) {
AddBadFlagsInfoBarIfNecessary(tab_contents);
AddObsoleteSystemInfoBarIfNecessary(tab_contents);
}
}
void BrowserInit::LaunchWithProfile::AddCrashedInfoBarIfNecessary(
Browser* browser,
TabContentsWrapper* tab) {
// Assume that if the user is launching incognito they were previously
// running incognito so that we have nothing to restore from.
if (HasPendingUncleanExit(profile_) && !profile_->IsOffTheRecord()) {
// The last session didn't exit cleanly. Show an infobar to the user
// so that they can restore if they want. The delegate deletes itself when
// it is closed.
tab->infobar_tab_helper()->AddInfoBar(
new SessionCrashedInfoBarDelegate(profile_, tab->infobar_tab_helper()));
}
}
void BrowserInit::LaunchWithProfile::AddBadFlagsInfoBarIfNecessary(
TabContentsWrapper* tab) {
// Unsupported flags for which to display a warning that "stability and
// security will suffer".
static const char* kBadFlags[] = {
// These imply disabling the sandbox.
switches::kSingleProcess,
switches::kNoSandbox,
switches::kInProcessWebGL,
// This should only be used for tests and to disable Protector on ChromeOS.
#if !defined(OS_CHROMEOS)
switches::kNoProtector,
#endif
NULL
};
const char* bad_flag = NULL;
for (const char** flag = kBadFlags; *flag; ++flag) {
if (command_line_.HasSwitch(*flag)) {
bad_flag = *flag;
break;
}
}
if (bad_flag) {
tab->infobar_tab_helper()->AddInfoBar(
new SimpleAlertInfoBarDelegate(
tab->infobar_tab_helper(), NULL,
l10n_util::GetStringFUTF16(
IDS_BAD_FLAGS_WARNING_MESSAGE,
UTF8ToUTF16(std::string("--") + bad_flag)),
false));
}
}
class LearnMoreInfoBar : public LinkInfoBarDelegate {
public:
LearnMoreInfoBar(InfoBarTabHelper* infobar_helper,
const string16& message,
const GURL& url);
virtual ~LearnMoreInfoBar();
virtual string16 GetMessageTextWithOffset(size_t* link_offset) const OVERRIDE;
virtual string16 GetLinkText() const OVERRIDE;
virtual bool LinkClicked(WindowOpenDisposition disposition) OVERRIDE;
private:
string16 message_;
GURL learn_more_url_;
DISALLOW_COPY_AND_ASSIGN(LearnMoreInfoBar);
};
LearnMoreInfoBar::LearnMoreInfoBar(InfoBarTabHelper* infobar_helper,
const string16& message,
const GURL& url)
: LinkInfoBarDelegate(infobar_helper),
message_(message),
learn_more_url_(url) {
}
LearnMoreInfoBar::~LearnMoreInfoBar() {
}
string16 LearnMoreInfoBar::GetMessageTextWithOffset(size_t* link_offset) const {
string16 text = message_;
text.push_back(' '); // Add a space before the following link.
*link_offset = text.size();
return text;
}
string16 LearnMoreInfoBar::GetLinkText() const {
return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
}
bool LearnMoreInfoBar::LinkClicked(WindowOpenDisposition disposition) {
OpenURLParams params(
learn_more_url_, Referrer(), disposition, content::PAGE_TRANSITION_LINK,
false);
owner()->web_contents()->OpenURL(params);
return false;
}
void BrowserInit::LaunchWithProfile::AddObsoleteSystemInfoBarIfNecessary(
TabContentsWrapper* tab) {
#if defined(TOOLKIT_GTK)
// We've deprecated support for Ubuntu Hardy. Rather than attempting to
// determine whether you're using that, we instead key off the GTK version;
// this will also deprecate other distributions (including variants of Ubuntu)
// that are of a similar age.
// Version key:
// Ubuntu Hardy: GTK 2.12
// RHEL 6: GTK 2.18
// Ubuntu Lucid: GTK 2.20
if (gtk_check_version(2, 18, 0)) {
string16 message = l10n_util::GetStringUTF16(IDS_SYSTEM_OBSOLETE_MESSAGE);
// Link to an article in the help center on minimum system requirements.
const char* kLearnMoreURL =
"http://www.google.com/support/chrome/bin/answer.py?answer=95411";
InfoBarTabHelper* infobar_helper = tab->infobar_tab_helper();
infobar_helper->AddInfoBar(
new LearnMoreInfoBar(infobar_helper,
message,
GURL(kLearnMoreURL)));
}
#endif
}
void BrowserInit::LaunchWithProfile::AddStartupURLs(
std::vector<GURL>* startup_urls) const {
// If we have urls specified beforehand (i.e. from command line) use them
// and nothing else.
if (!startup_urls->empty())
return;
// If we have urls specified by the first run master preferences use them
// and nothing else.
if (browser_init_) {
if (!browser_init_->first_run_tabs_.empty()) {
std::vector<GURL>::iterator it = browser_init_->first_run_tabs_.begin();
while (it != browser_init_->first_run_tabs_.end()) {
// Replace magic names for the actual urls.
if (it->host() == "new_tab_page") {
startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
} else if (it->host() == "welcome_page") {
startup_urls->push_back(GetWelcomePageURL());
} else {
startup_urls->push_back(*it);
}
++it;
}
browser_init_->first_run_tabs_.clear();
}
}
// Otherwise open at least the new tab page (and the welcome page, if this
// is the first time the browser is being started), or the set of URLs
// specified on the command line.
if (startup_urls->empty()) {
startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
PrefService* prefs = g_browser_process->local_state();
if (prefs->FindPreference(prefs::kShouldShowWelcomePage) &&
prefs->GetBoolean(prefs::kShouldShowWelcomePage)) {
// Reset the preference so we don't show the welcome page next time.
prefs->ClearPref(prefs::kShouldShowWelcomePage);
startup_urls->push_back(GetWelcomePageURL());
}
}
// If the sync promo page is going to be displayed then insert it at the front
// of the list.
if (SyncPromoUI::ShouldShowSyncPromoAtStartup(profile_, is_first_run_)) {
SyncPromoUI::DidShowSyncPromoAtStartup(profile_);
GURL old_url = (*startup_urls)[0];
(*startup_urls)[0] =
SyncPromoUI::GetSyncPromoURL(GURL(chrome::kChromeUINewTabURL),
SyncPromoUI::SOURCE_START_PAGE);
// An empty URL means to go to the home page.
if (old_url.is_empty() &&
profile_->GetHomePage() == GURL(chrome::kChromeUINewTabURL)) {
old_url = GURL(chrome::kChromeUINewTabURL);
}
// If the old URL is not the NTP then insert it right after the sync promo.
if (old_url != GURL(chrome::kChromeUINewTabURL))
startup_urls->insert(startup_urls->begin() + 1, old_url);
// If we have more than two startup tabs then skip the welcome page.
if (startup_urls->size() > 2) {
std::vector<GURL>::iterator it = std::find(
startup_urls->begin(), startup_urls->end(), GetWelcomePageURL());
if (it != startup_urls->end())
startup_urls->erase(it);
}
}
}
void BrowserInit::LaunchWithProfile::CheckDefaultBrowser(Profile* profile) {
// We do not check if we are the default browser if:
// - the user said "don't ask me again" on the infobar earlier.
// - this is the first launch after the first run flow.
// - There is a policy in control of this setting.
if (!profile->GetPrefs()->GetBoolean(prefs::kCheckDefaultBrowser) ||
is_first_run_) {
return;
}
if (g_browser_process->local_state()->IsManagedPreference(
prefs::kDefaultBrowserSettingEnabled)) {
if (g_browser_process->local_state()->GetBoolean(
prefs::kDefaultBrowserSettingEnabled)) {
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(
base::IgnoreResult(&ShellIntegration::SetAsDefaultBrowser)));
} else {
// TODO(pastarmovj): We can't really do anything meaningful here yet but
// just prevent showing the infobar.
}
return;
}
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
base::Bind(&CheckDefaultBrowserCallback));
}
bool BrowserInit::LaunchWithProfile::CheckIfAutoLaunched(Profile* profile) {
#if defined(OS_WIN)
if (!auto_launch_trial::IsInAutoLaunchGroup())
return false;
// Only supported on the main profile for now.
if (profile->GetPath().BaseName().value() !=
ASCIIToUTF16(chrome::kInitialProfile)) {
return false;
}
int infobar_shown =
profile->GetPrefs()->GetInteger(prefs::kShownAutoLaunchInfobar);
if (infobar_shown >= kMaxInfobarShown)
return false;
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kChromeFrame))
return false;
if (command_line.HasSwitch(switches::kAutoLaunchAtStartup) ||
first_run::IsChromeFirstRun()) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&CheckAutoLaunchCallback, profile));
return true;
}
#endif
return false;
}
void BrowserInit::LaunchWithProfile::CheckPreferencesBackup(Profile* profile) {
ProtectorService* protector_service =
ProtectorServiceFactory::GetForProfile(profile);
ProtectedPrefsWatcher* prefs_watcher = protector_service->GetPrefsWatcher();
// Check if backup is valid.
if (!prefs_watcher->is_backup_valid()) {
protector_service->ShowChange(protector::CreatePrefsBackupInvalidChange());
// Further checks make no sense.
return;
}
// Check for session startup (including pinned tabs) changes.
if (SessionStartupPref::DidStartupPrefChange(profile) ||
prefs_watcher->DidPrefChange(prefs::kPinnedTabs)) {
LOG(WARNING) << "Session startup settings have changed";
SessionStartupPref new_pref = SessionStartupPref::GetStartupPref(profile);
PinnedTabCodec::Tabs new_tabs = PinnedTabCodec::ReadPinnedTabs(profile);
const base::Value* tabs_backup =
prefs_watcher->GetBackupForPref(prefs::kPinnedTabs);
protector_service->ShowChange(protector::CreateSessionStartupChange(
new_pref,
new_tabs,
SessionStartupPref::GetStartupPrefBackup(profile),
PinnedTabCodec::ReadPinnedTabs(tabs_backup)));
}
// Check for homepage changes.
if (prefs_watcher->DidPrefChange(prefs::kHomePage) ||
prefs_watcher->DidPrefChange(prefs::kHomePageIsNewTabPage) ||
prefs_watcher->DidPrefChange(prefs::kShowHomeButton)) {
LOG(WARNING) << "Homepage has changed";
PrefService* prefs = profile->GetPrefs();
std::string backup_homepage;
bool backup_homepage_is_ntp;
bool backup_show_home_button;
if (!prefs_watcher->GetBackupForPref(prefs::kHomePage)->
GetAsString(&backup_homepage) ||
!prefs_watcher->GetBackupForPref(prefs::kHomePageIsNewTabPage)->
GetAsBoolean(&backup_homepage_is_ntp) ||
!prefs_watcher->GetBackupForPref(prefs::kShowHomeButton)->
GetAsBoolean(&backup_show_home_button)) {
NOTREACHED();
}
protector_service->ShowChange(protector::CreateHomepageChange(
// New:
prefs->GetString(prefs::kHomePage),
prefs->GetBoolean(prefs::kHomePageIsNewTabPage),
prefs->GetBoolean(prefs::kShowHomeButton),
// Backup:
backup_homepage,
backup_homepage_is_ntp,
backup_show_home_button));
}
}
std::vector<GURL> BrowserInit::GetURLsFromCommandLine(
const CommandLine& command_line,
const FilePath& cur_dir,
Profile* profile) {
std::vector<GURL> urls;
const CommandLine::StringVector& params = command_line.GetArgs();
for (size_t i = 0; i < params.size(); ++i) {
FilePath param = FilePath(params[i]);
// Handle Vista way of searching - "? <search-term>"
if (param.value().size() > 2 &&
param.value()[0] == '?' && param.value()[1] == ' ') {
const TemplateURL* default_provider =
TemplateURLServiceFactory::GetForProfile(profile)->
GetDefaultSearchProvider();
if (default_provider) {
const TemplateURLRef& search_url = default_provider->url_ref();
DCHECK(search_url.SupportsReplacement());
string16 search_term = param.LossyDisplayName().substr(2);
urls.push_back(GURL(search_url.ReplaceSearchTermsUsingProfile(
profile, search_term, TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
string16())));
continue;
}
}
// Otherwise, fall through to treating it as a URL.
// This will create a file URL or a regular URL.
// This call can (in rare circumstances) block the UI thread.
// Allow it until this bug is fixed.
// http://code.google.com/p/chromium/issues/detail?id=60641
GURL url;
{
base::ThreadRestrictions::ScopedAllowIO allow_io;
url = URLFixerUpper::FixupRelativeFile(cur_dir, param);
}
// Exclude dangerous schemes.
if (url.is_valid()) {
ChildProcessSecurityPolicy *policy =
ChildProcessSecurityPolicy::GetInstance();
if (policy->IsWebSafeScheme(url.scheme()) ||
url.SchemeIs(chrome::kFileScheme) ||
#if defined(OS_CHROMEOS)
// In ChromeOS, allow a settings page to be specified on the
// command line. See ExistingUserController::OnLoginSuccess.
(url.spec().find(chrome::kChromeUISettingsURL) == 0) ||
#endif
(url.spec().compare(chrome::kAboutBlankURL) == 0)) {
urls.push_back(url);
}
}
}
#if defined(OS_WIN)
// If we are in Windows 8 metro mode and were launched as a result of the
// search charm or via a url navigation in metro, then fetch the url being
// navigated to from the metro handler and initiate the navigation
// accordingly.
if (urls.empty()) {
HMODULE metro = base::win::GetMetroModule();
if (metro) {
GetInitialUrl initial_metro_url = reinterpret_cast<GetInitialUrl>(
::GetProcAddress(metro, "GetInitialUrl"));
string16 url = initial_metro_url();
if (!url.empty())
urls.push_back(GURL(url));
}
}
#endif // OS_WIN
return urls;
}
bool BrowserInit::ProcessCmdLineImpl(
const CommandLine& command_line,
const FilePath& cur_dir,
bool process_startup,
Profile* last_used_profile,
const Profiles& last_opened_profiles,
int* return_code,
BrowserInit* browser_init) {
DCHECK(last_used_profile);
if (process_startup) {
if (command_line.HasSwitch(switches::kDisablePromptOnRepost))
content::NavigationController::DisablePromptOnRepost();
RegisterComponentsForUpdate(command_line);
}
bool silent_launch = false;
#if defined(ENABLE_AUTOMATION)
// Look for the testing channel ID ONLY during process startup
if (process_startup &&
command_line.HasSwitch(switches::kTestingChannelID)) {
std::string testing_channel_id = command_line.GetSwitchValueASCII(
switches::kTestingChannelID);
// TODO(sanjeevr) Check if we need to make this a singleton for
// compatibility with the old testing code
// If there are any extra parameters, we expect each one to generate a
// new tab; if there are none then we get one homepage tab.
int expected_tab_count = 1;
if (command_line.HasSwitch(switches::kNoStartupWindow) &&
!command_line.HasSwitch(switches::kAutoLaunchAtStartup)) {
expected_tab_count = 0;
#if defined(OS_CHROMEOS)
// kLoginManager will cause Chrome to start up with the ChromeOS login
// screen instead of a browser window, so it won't load any tabs.
} else if (command_line.HasSwitch(switches::kLoginManager)) {
expected_tab_count = 0;
#endif
} else if (command_line.HasSwitch(switches::kRestoreLastSession)) {
std::string restore_session_value(
command_line.GetSwitchValueASCII(switches::kRestoreLastSession));
base::StringToInt(restore_session_value, &expected_tab_count);
} else {
std::vector<GURL> urls_to_open = GetURLsFromCommandLine(
command_line, cur_dir, last_used_profile);
expected_tab_count =
std::max(1, static_cast<int>(urls_to_open.size()));
}
if (!CreateAutomationProvider<TestingAutomationProvider>(
testing_channel_id,
last_used_profile,
static_cast<size_t>(expected_tab_count)))
return false;
}
if (command_line.HasSwitch(switches::kAutomationClientChannelID)) {
std::string automation_channel_id = command_line.GetSwitchValueASCII(
switches::kAutomationClientChannelID);
// If there are any extra parameters, we expect each one to generate a
// new tab; if there are none then we have no tabs
std::vector<GURL> urls_to_open = GetURLsFromCommandLine(
command_line, cur_dir, last_used_profile);
size_t expected_tabs =
std::max(static_cast<int>(urls_to_open.size()), 0);
if (expected_tabs == 0)
silent_launch = true;
if (command_line.HasSwitch(switches::kChromeFrame)) {
#if !defined(USE_AURA)
if (!CreateAutomationProvider<ChromeFrameAutomationProvider>(
automation_channel_id, last_used_profile, expected_tabs))
return false;
#endif
} else {
if (!CreateAutomationProvider<AutomationProvider>(
automation_channel_id, last_used_profile, expected_tabs))
return false;
}
}
#endif // defined(ENABLE_AUTOMATION)
// If we have been invoked to display a desktop notification on behalf of
// the service process, we do not want to open any browser windows.
if (command_line.HasSwitch(switches::kNotifyCloudPrintTokenExpired)) {
silent_launch = true;
CloudPrintProxyServiceFactory::GetForProfile(last_used_profile)->
ShowTokenExpiredNotification();
}
// If we are just displaying a print dialog we shouldn't open browser
// windows.
if (command_line.HasSwitch(switches::kCloudPrintFile) &&
print_dialog_cloud::CreatePrintDialogFromCommandLine(command_line)) {
silent_launch = true;
}
// If we are checking the proxy enabled policy, don't open any windows.
if (command_line.HasSwitch(switches::kCheckCloudPrintConnectorPolicy)) {
silent_launch = true;
if (CloudPrintProxyServiceFactory::GetForProfile(last_used_profile)->
EnforceCloudPrintConnectorPolicyAndQuit())
// Success, nothing more needs to be done, so return false to stop
// launching and quit.
return false;
}
if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
std::string allowed_ports =
command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
net::SetExplicitlyAllowedPorts(allowed_ports);
}
#if defined(OS_CHROMEOS)
// The browser will be launched after the user logs in.
if (command_line.HasSwitch(switches::kLoginManager) ||
command_line.HasSwitch(switches::kLoginPassword)) {
silent_launch = true;
}
#endif
#if defined(TOOLKIT_VIEWS) && defined(OS_LINUX)
// Get a list of pointer-devices that should be treated as touch-devices.
// This is primarily used for testing/debugging touch-event processing when a
// touch-device isn't available.
std::string touch_devices =
command_line.GetSwitchValueASCII(switches::kTouchDevices);
if (!touch_devices.empty()) {
std::vector<std::string> devs;
std::vector<unsigned int> device_ids;
unsigned int devid;
base::SplitString(touch_devices, ',', &devs);
for (std::vector<std::string>::iterator iter = devs.begin();
iter != devs.end(); ++iter) {
if (base::StringToInt(*iter, reinterpret_cast<int*>(&devid)))
device_ids.push_back(devid);
else
DLOG(WARNING) << "Invalid touch-device id: " << *iter;
}
ui::TouchFactory::GetInstance()->SetTouchDeviceList(device_ids);
}
#endif
// If we don't want to launch a new browser window or tab (in the case
// of an automation request), we are done here.
if (!silent_launch) {
IsProcessStartup is_process_startup = process_startup ?
IS_PROCESS_STARTUP : IS_NOT_PROCESS_STARTUP;
IsFirstRun is_first_run = first_run::IsChromeFirstRun() ?
IS_FIRST_RUN : IS_NOT_FIRST_RUN;
// |last_opened_profiles| will be empty in the following circumstances:
// - This is the first launch. |last_used_profile| is the initial profile.
// - The user exited the browser by closing all windows for all
// profiles. |last_used_profile| is the profile which owned the last open
// window.
// - Only incognito windows were open when the browser exited.
// |last_used_profile| is the last used incognito profile. Restoring it will
// create a browser window for the corresponding original profile.
if (last_opened_profiles.empty()) {
if (!browser_init->LaunchBrowser(command_line, last_used_profile, cur_dir,
is_process_startup, is_first_run, return_code))
return false;
} else {
// Launch the last used profile with the full command line, and the other
// opened profiles without the URLs to launch.
CommandLine command_line_without_urls(command_line.GetProgram());
const CommandLine::SwitchMap& switches = command_line.GetSwitches();
for (CommandLine::SwitchMap::const_iterator switch_it = switches.begin();
switch_it != switches.end(); ++switch_it) {
command_line_without_urls.AppendSwitchNative(switch_it->first,
switch_it->second);
}
// Launch the profiles in the order they became active.
for (Profiles::const_iterator it = last_opened_profiles.begin();
it != last_opened_profiles.end(); ++it) {
// Don't launch additional profiles which would only open a new tab
// page. When restarting after an update, all profiles will reopen last
// open pages.
SessionStartupPref startup_pref =
GetSessionStartupPref(command_line, *it);
if (*it != last_used_profile &&
startup_pref.type == SessionStartupPref::DEFAULT &&
!HasPendingUncleanExit(*it))
continue;
if (!browser_init->LaunchBrowser((*it == last_used_profile) ?
command_line : command_line_without_urls, *it, cur_dir,
is_process_startup, is_first_run, return_code))
return false;
// We've launched at least one browser.
is_process_startup = BrowserInit::IS_NOT_PROCESS_STARTUP;
}
}
}
return true;
}
template <class AutomationProviderClass>
bool BrowserInit::CreateAutomationProvider(const std::string& channel_id,
Profile* profile,
size_t expected_tabs) {
#if defined(ENABLE_AUTOMATION)
scoped_refptr<AutomationProviderClass> automation =
new AutomationProviderClass(profile);
if (!automation->InitializeChannel(channel_id))
return false;
automation->SetExpectedTabCount(expected_tabs);
AutomationProviderList* list = g_browser_process->GetAutomationProviderList();
DCHECK(list);
list->AddProvider(automation);
#endif // defined(ENABLE_AUTOMATION)
return true;
}
// static
void BrowserInit::ProcessCommandLineOnProfileCreated(
const CommandLine& cmd_line,
const FilePath& cur_dir,
Profile* profile,
Profile::CreateStatus status) {
if (status == Profile::CREATE_STATUS_INITIALIZED)
ProcessCmdLineImpl(cmd_line, cur_dir, false, profile, Profiles(), NULL,
NULL);
}
// static
void BrowserInit::ProcessCommandLineAlreadyRunning(const CommandLine& cmd_line,
const FilePath& cur_dir) {
if (cmd_line.HasSwitch(switches::kProfileDirectory)) {
ProfileManager* profile_manager = g_browser_process->profile_manager();
FilePath path = cmd_line.GetSwitchValuePath(switches::kProfileDirectory);
path = profile_manager->user_data_dir().Append(path);
profile_manager->CreateProfileAsync(path,
base::Bind(&BrowserInit::ProcessCommandLineOnProfileCreated,
cmd_line, cur_dir));
return;
}
Profile* profile = ProfileManager::GetLastUsedProfile();
if (!profile) {
// We should only be able to get here if the profile already exists and
// has been created.
NOTREACHED();
return;
}
ProcessCmdLineImpl(cmd_line, cur_dir, false, profile, Profiles(), NULL, NULL);
}
|