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
|
// 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.
#import "chrome/browser/app_controller_mac.h"
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/mac/foundation_util.h"
#include "base/mac/mac_util.h"
#include "base/mac/sdk_forward_declarations.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/apps/app_shim/extension_app_shim_handler_mac.h"
#include "chrome/browser/apps/app_window_registry_util.h"
#include "chrome/browser/background/background_application_list_model.h"
#include "chrome/browser/background/background_mode_manager.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/command_updater.h"
#include "chrome/browser/download/download_service.h"
#include "chrome/browser/download/download_service_factory.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/mac/mac_startup_profiler.h"
#include "chrome/browser/prefs/incognito_mode_prefs.h"
#include "chrome/browser/profiles/profile_info_cache_observer.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profiles_state.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/sessions/tab_restore_service.h"
#include "chrome/browser/sessions/tab_restore_service_factory.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/signin/signin_promo.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/sync_ui_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_command_controller.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_iterator.h"
#include "chrome/browser/ui/browser_mac.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/chrome_pages.h"
#import "chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.h"
#include "chrome/browser/ui/cocoa/apps/quit_with_apps_controller_mac.h"
#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
#import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
#import "chrome/browser/ui/cocoa/browser_window_controller.h"
#import "chrome/browser/ui/cocoa/confirm_quit.h"
#import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
#import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
#include "chrome/browser/ui/cocoa/handoff_active_url_observer_bridge.h"
#import "chrome/browser/ui/cocoa/history_menu_bridge.h"
#include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
#import "chrome/browser/ui/cocoa/profiles/profile_menu_controller.h"
#import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
#import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
#include "chrome/browser/ui/cocoa/task_manager_mac.h"
#include "chrome/browser/ui/extensions/application_launch.h"
#include "chrome/browser/ui/host_desktop.h"
#include "chrome/browser/ui/startup/startup_browser_creator.h"
#include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
#include "chrome/browser/ui/user_manager.h"
#include "chrome/browser/web_applications/web_app_mac.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/cloud_print/cloud_print_class_mac.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/mac/app_mode_common.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "components/handoff/handoff_manager.h"
#include "components/handoff/handoff_utility.h"
#include "components/signin/core/browser/signin_manager.h"
#include "components/signin/core/common/profile_management_switches.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/user_metrics.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extension_registry.h"
#include "net/base/filename_util.h"
#include "ui/base/cocoa/focus_window_set.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/l10n_util_mac.h"
using apps::AppShimHandler;
using apps::ExtensionAppShimHandler;
using base::UserMetricsAction;
using content::BrowserContext;
using content::BrowserThread;
using content::DownloadManager;
namespace {
// Declare notification names from the 10.7 SDK.
#if !defined(MAC_OS_X_VERSION_10_7) || \
MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
NSString* NSPopoverDidShowNotification = @"NSPopoverDidShowNotification";
NSString* NSPopoverDidCloseNotification = @"NSPopoverDidCloseNotification";
#endif
// How long we allow a workspace change notification to wait to be
// associated with a dock activation. The animation lasts 250ms. See
// applicationShouldHandleReopen:hasVisibleWindows:.
static const int kWorkspaceChangeTimeoutMs = 500;
// True while AppController is calling chrome::NewEmptyWindow(). We need a
// global flag here, analogue to StartupBrowserCreator::InProcessStartup()
// because otherwise the SessionService will try to restore sessions when we
// make a new window while there are no other active windows.
bool g_is_opening_new_window = false;
// Activates a browser window having the given profile (the last one active) if
// possible and returns a pointer to the activate |Browser| or NULL if this was
// not possible. If the last active browser is minimized (in particular, if
// there are only minimized windows), it will unminimize it.
Browser* ActivateBrowser(Profile* profile) {
Browser* browser = chrome::FindLastActiveWithProfile(
profile->IsGuestSession() ? profile->GetOffTheRecordProfile() : profile,
chrome::HOST_DESKTOP_TYPE_NATIVE);
if (browser)
browser->window()->Activate();
return browser;
}
// Creates an empty browser window with the given profile and returns a pointer
// to the new |Browser|.
Browser* CreateBrowser(Profile* profile) {
{
base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
chrome::NewEmptyWindow(profile, chrome::HOST_DESKTOP_TYPE_NATIVE);
}
Browser* browser = chrome::GetLastActiveBrowser();
CHECK(browser);
return browser;
}
// Activates a browser window having the given profile (the last one active) if
// possible or creates an empty one if necessary. Returns a pointer to the
// activated/new |Browser|.
Browser* ActivateOrCreateBrowser(Profile* profile) {
if (Browser* browser = ActivateBrowser(profile))
return browser;
return CreateBrowser(profile);
}
CFStringRef BaseBundleID_CFString() {
NSString* base_bundle_id =
[NSString stringWithUTF8String:base::mac::BaseBundleID()];
return base::mac::NSToCFCast(base_bundle_id);
}
// This callback synchronizes preferences (under "org.chromium.Chromium" or
// "com.google.Chrome"), in particular, writes them out to disk.
void PrefsSyncCallback() {
if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
LOG(WARNING) << "Error recording application bundle path.";
}
// Record the location of the application bundle (containing the main framework)
// from which Chromium was loaded. This is used by app mode shims to find
// Chromium.
void RecordLastRunAppBundlePath() {
// Going up three levels from |chrome::GetVersionedDirectory()| gives the
// real, user-visible app bundle directory. (The alternatives give either the
// framework's path or the initial app's path, which may be an app mode shim
// or a unit test.)
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
base::FilePath app_bundle_path =
chrome::GetVersionedDirectory().DirName().DirName().DirName();
base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring(
base::SysUTF8ToCFStringRef(app_bundle_path.value()));
CFPreferencesSetAppValue(
base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
app_bundle_path_cfstring, BaseBundleID_CFString());
// Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
BrowserThread::PostDelayedTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&PrefsSyncCallback),
base::TimeDelta::FromMilliseconds(1500));
}
bool IsProfileSignedOut(Profile* profile) {
// The signed out status only makes sense at the moment in the context of the
// --new-profile-management flag.
if (!switches::IsNewProfileManagement())
return false;
ProfileInfoCache& cache =
g_browser_process->profile_manager()->GetProfileInfoCache();
size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath());
if (profile_index == std::string::npos)
return false;
return cache.ProfileIsSigninRequiredAtIndex(profile_index);
}
} // namespace
@interface AppController () <HandoffActiveURLObserverBridgeDelegate>
- (void)initMenuState;
- (void)initProfileMenu;
- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
- (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item;
- (void)registerServicesMenuTypesTo:(NSApplication*)app;
- (void)getUrl:(NSAppleEventDescriptor*)event
withReply:(NSAppleEventDescriptor*)reply;
- (void)windowLayeringDidChange:(NSNotification*)inNotification;
- (void)activeSpaceDidChange:(NSNotification*)inNotification;
- (void)checkForAnyKeyWindows;
- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
- (BOOL)shouldQuitWithInProgressDownloads;
- (void)executeApplication:(id)sender;
- (void)profileWasRemoved:(const base::FilePath&)profilePath;
// Opens a tab for each GURL in |urls|.
- (void)openUrls:(const std::vector<GURL>&)urls;
// This class cannot open urls until startup has finished. The urls that cannot
// be opened are cached in |startupUrls_|. This method must be called exactly
// once after startup has completed. It opens the urls in |startupUrls_|, and
// clears |startupUrls_|.
- (void)openStartupUrls;
// Opens a tab for each GURL in |urls|. If there is exactly one tab open before
// this method is called, and that tab is the NTP, then this method closes the
// NTP after all the |urls| have been opened.
- (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls;
// Whether instances of this class should use the Handoff feature.
- (BOOL)shouldUseHandoff;
// This method passes |handoffURL| to |handoffManager_|.
- (void)passURLToHandoffManager:(const GURL&)handoffURL;
// Lazily creates the Handoff Manager. Updates the state of the Handoff
// Manager. This method is idempotent. This should be called:
// - During initialization.
// - When the current tab navigates to a new URL.
// - When the active browser changes.
// - When the active browser's active tab switches.
// |webContents| should be the new, active WebContents.
- (void)updateHandoffManager:(content::WebContents*)webContents;
// Given |webContents|, extracts a GURL to be used for Handoff. This may return
// the empty GURL.
- (GURL)handoffURLFromWebContents:(content::WebContents*)webContents;
@end
class AppControllerProfileObserver : public ProfileInfoCacheObserver {
public:
AppControllerProfileObserver(
ProfileManager* profile_manager, AppController* app_controller)
: profile_manager_(profile_manager),
app_controller_(app_controller) {
DCHECK(profile_manager_);
DCHECK(app_controller_);
profile_manager_->GetProfileInfoCache().AddObserver(this);
}
~AppControllerProfileObserver() override {
DCHECK(profile_manager_);
profile_manager_->GetProfileInfoCache().RemoveObserver(this);
}
private:
// ProfileInfoCacheObserver implementation:
void OnProfileAdded(const base::FilePath& profile_path) override {}
void OnProfileWasRemoved(const base::FilePath& profile_path,
const base::string16& profile_name) override {
// When a profile is deleted we need to notify the AppController,
// so it can correctly update its pointer to the last used profile.
[app_controller_ profileWasRemoved:profile_path];
}
void OnProfileWillBeRemoved(const base::FilePath& profile_path) override {}
void OnProfileNameChanged(const base::FilePath& profile_path,
const base::string16& old_profile_name) override {}
void OnProfileAvatarChanged(const base::FilePath& profile_path) override {}
ProfileManager* profile_manager_;
AppController* app_controller_; // Weak; owns us.
DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
};
@implementation AppController
@synthesize startupComplete = startupComplete_;
// This method is called very early in application startup (ie, before
// the profile is loaded or any preferences have been registered). Defer any
// user-data initialization until -applicationDidFinishLaunching:.
- (void)awakeFromNib {
MacStartupProfiler::GetInstance()->Profile(
MacStartupProfiler::AWAKE_FROM_NIB);
// We need to register the handlers early to catch events fired on launch.
NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
[em setEventHandler:self
andSelector:@selector(getUrl:withReply:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];
[em setEventHandler:self
andSelector:@selector(getUrl:withReply:)
forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
andEventID:'OURL']; // back to the Spyglass days.
// Register for various window layering changes. We use these to update
// various UI elements (command-key equivalents, etc) when the frontmost
// window changes.
NSNotificationCenter* notificationCenter =
[NSNotificationCenter defaultCenter];
[notificationCenter
addObserver:self
selector:@selector(windowLayeringDidChange:)
name:NSWindowDidBecomeKeyNotification
object:nil];
[notificationCenter
addObserver:self
selector:@selector(windowLayeringDidChange:)
name:NSWindowDidResignKeyNotification
object:nil];
[notificationCenter
addObserver:self
selector:@selector(windowLayeringDidChange:)
name:NSWindowDidBecomeMainNotification
object:nil];
[notificationCenter
addObserver:self
selector:@selector(windowLayeringDidChange:)
name:NSWindowDidResignMainNotification
object:nil];
if (base::mac::IsOSLionOrLater()) {
[notificationCenter
addObserver:self
selector:@selector(popoverDidShow:)
name:NSPopoverDidShowNotification
object:nil];
[notificationCenter
addObserver:self
selector:@selector(popoverDidClose:)
name:NSPopoverDidCloseNotification
object:nil];
}
// Register for space change notifications.
[[[NSWorkspace sharedWorkspace] notificationCenter]
addObserver:self
selector:@selector(activeSpaceDidChange:)
name:NSWorkspaceActiveSpaceDidChangeNotification
object:nil];
// Set up the command updater for when there are no windows open
[self initMenuState];
// Initialize the Profile menu.
[self initProfileMenu];
}
- (void)unregisterEventHandlers {
NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
[em removeEventHandlerForEventClass:kInternetEventClass
andEventID:kAEGetURL];
[em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
andEventID:cloud_print::kAECloudPrintClass];
[em removeEventHandlerForEventClass:'WWW!'
andEventID:'OURL'];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
}
// (NSApplicationDelegate protocol) This is the Apple-approved place to override
// the default handlers.
- (void)applicationWillFinishLaunching:(NSNotification*)notification {
MacStartupProfiler::GetInstance()->Profile(
MacStartupProfiler::WILL_FINISH_LAUNCHING);
}
- (void)applicationWillHide:(NSNotification*)notification {
apps::ExtensionAppShimHandler::OnChromeWillHide();
}
- (BOOL)tryToTerminateApplication:(NSApplication*)app {
// Check for in-process downloads, and prompt the user if they really want
// to quit (and thus cancel downloads). Only check if we're not already
// shutting down, else the user might be prompted multiple times if the
// download isn't stopped before terminate is called again.
if (!browser_shutdown::IsTryingToQuit() &&
![self shouldQuitWithInProgressDownloads])
return NO;
// TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
// them in, but I'm not sure about UX; we'd also want to disable other things
// though.) http://crbug.com/40861
// Check if the user really wants to quit by employing the confirm-to-quit
// mechanism.
if (!browser_shutdown::IsTryingToQuit() &&
[self applicationShouldTerminate:app] != NSTerminateNow)
return NO;
// Check for active apps. If quitting is prevented, only close browsers and
// sessions.
if (!browser_shutdown::IsTryingToQuit() && quitWithAppsController_.get() &&
!quitWithAppsController_->ShouldQuit()) {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kHostedAppQuitNotification)) {
return NO;
}
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
content::NotificationService::AllSources(),
content::NotificationService::NoDetails());
// This will close all browser sessions.
chrome::CloseAllBrowsers();
return NO;
}
size_t num_browsers = chrome::GetTotalBrowserCount();
// Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
// already shutting down.
if (!browser_shutdown::IsTryingToQuit()) {
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
content::NotificationService::AllSources(),
content::NotificationService::NoDetails());
chrome::CloseAllBrowsersAndQuit();
}
return num_browsers == 0 ? YES : NO;
}
- (void)stopTryingToTerminateApplication:(NSApplication*)app {
if (browser_shutdown::IsTryingToQuit()) {
// Reset the "trying to quit" state, so that closing all browser windows
// will no longer lead to termination.
browser_shutdown::SetTryingToQuit(false);
// TODO(viettrungluu): Were we to remove Apple Event handlers above, we
// would have to reinstall them here. http://crbug.com/40861
}
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
// If there are no windows, quit immediately.
if (chrome::BrowserIterator().done() &&
!AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile(0)) {
return NSTerminateNow;
}
// Check if the preference is turned on.
const PrefService* prefs = g_browser_process->local_state();
if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
return NSTerminateNow;
}
// If the application is going to terminate as the result of a Cmd+Q
// invocation, use the special sauce to prevent accidental quitting.
// http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
// This logic is only for keyboard-initiated quits.
if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
return NSTerminateNow;
return [[ConfirmQuitPanelController sharedController]
runModalLoopForApplication:app];
}
// Called when the app is shutting down. Clean-up as appropriate.
- (void)applicationWillTerminate:(NSNotification*)aNotification {
// There better be no browser windows left at this point.
CHECK_EQ(0u, chrome::GetTotalBrowserCount());
// Tell BrowserList not to keep the browser process alive. Once all the
// browsers get dealloc'd, it will stop the RunLoop and fall back into main().
chrome::DecrementKeepAliveCount();
// Reset all pref watching, as this object outlives the prefs system.
profilePrefRegistrar_.reset();
localPrefRegistrar_.RemoveAll();
[self unregisterEventHandlers];
appShimMenuController_.reset();
STLDeleteContainerPairSecondPointers(profileBookmarkMenuBridgeMap_.begin(),
profileBookmarkMenuBridgeMap_.end());
}
- (void)didEndMainMessageLoop {
DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile],
chrome::HOST_DESKTOP_TYPE_NATIVE));
if (!chrome::GetBrowserCount([self lastProfile],
chrome::HOST_DESKTOP_TYPE_NATIVE)) {
// As we're shutting down, we need to nuke the TabRestoreService, which
// will start the shutdown of the NavigationControllers and allow for
// proper shutdown. If we don't do this, Chrome won't shut down cleanly,
// and may end up crashing when some thread tries to use the IO thread (or
// another thread) that is no longer valid.
TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
}
}
// If the window has a tab controller, make "close window" be cmd-shift-w,
// otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
// affects whether the shift modifier is used.
- (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
[closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
@"w")];
[closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
}
// If the window has a tab controller, make "close tab" take over cmd-w,
// otherwise it shouldn't have any key-equivalent because it should be disabled.
- (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
if (enableCloseTabShortcut) {
[closeTabMenuItem_ setKeyEquivalent:@"w"];
[closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
} else {
[closeTabMenuItem_ setKeyEquivalent:@""];
[closeTabMenuItem_ setKeyEquivalentModifierMask:0];
}
}
// Explicitly remove any command-key equivalents from the close tab/window
// menus so that nothing can go haywire if we get a user action during pending
// updates.
- (void)clearCloseMenuItemKeyEquivalents {
[closeTabMenuItem_ setKeyEquivalent:@""];
[closeTabMenuItem_ setKeyEquivalentModifierMask:0];
[closeWindowMenuItem_ setKeyEquivalent:@""];
[closeWindowMenuItem_ setKeyEquivalentModifierMask:0];
}
// See if the focused window window has tabs, and adjust the key equivalents for
// Close Tab/Close Window accordingly.
- (void)fixCloseMenuItemKeyEquivalents {
fileMenuUpdatePending_ = NO;
NSWindow* window = [NSApp keyWindow];
NSWindow* mainWindow = [NSApp mainWindow];
if (!window || ([window parentWindow] == mainWindow)) {
// If the key window is a child of the main window (e.g. a bubble), the main
// window should be the one that handles the close menu item action.
// Also, there might be a small amount of time where there is no key window;
// in that case as well, just use our main browser window if there is one.
// You might think that we should just always use the main window, but the
// "About Chrome" window serves as a counterexample.
window = mainWindow;
}
BOOL hasTabs =
[[window windowController] isKindOfClass:[TabWindowController class]];
BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
[self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
[self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
}
// Fix up the "close tab/close window" command-key equivalents. We do this
// after a delay to ensure that window layer state has been set by the time
// we do the enabling. This should only be called on the main thread, code that
// calls this (even as a side-effect) from other threads needs to be fixed.
- (void)delayedFixCloseMenuItemKeyEquivalents {
DCHECK([NSThread isMainThread]);
if (!fileMenuUpdatePending_) {
// The OS prefers keypresses to timers, so it's possible that a cmd-w
// can sneak in before this timer fires. In order to prevent that from
// having any bad consequences, just clear the keys combos altogether. They
// will be reset when the timer eventually fires.
if ([NSThread isMainThread]) {
fileMenuUpdatePending_ = YES;
[self clearCloseMenuItemKeyEquivalents];
[self performSelector:@selector(fixCloseMenuItemKeyEquivalents)
withObject:nil
afterDelay:0];
} else {
// This shouldn't be happening, but if it does, force it to the main
// thread to avoid dropping the update. Don't mess with
// |fileMenuUpdatePending_| as it's not expected to be threadsafe and
// there could be a race between the selector finishing and setting the
// flag.
[self
performSelectorOnMainThread:@selector(fixCloseMenuItemKeyEquivalents)
withObject:nil
waitUntilDone:NO];
}
}
}
// Called when we get a notification about the window layering changing to
// update the UI based on the new main window.
- (void)windowLayeringDidChange:(NSNotification*)notify {
[self delayedFixCloseMenuItemKeyEquivalents];
if ([notify name] == NSWindowDidResignKeyNotification) {
// If a window is closed, this notification is fired but |[NSApp keyWindow]|
// returns nil regardless of whether any suitable candidates for the key
// window remain. It seems that the new key window for the app is not set
// until after this notification is fired, so a check is performed after the
// run loop is allowed to spin.
[self performSelector:@selector(checkForAnyKeyWindows)
withObject:nil
afterDelay:0.0];
}
// If the window changed to a new BrowserWindowController, update the profile.
id windowController = [[notify object] windowController];
if (![windowController isKindOfClass:[BrowserWindowController class]])
return;
if ([notify name] == NSWindowDidBecomeMainNotification) {
// If the profile is incognito, use the original profile.
Profile* newProfile = [windowController profile]->GetOriginalProfile();
[self windowChangedToProfile:newProfile];
} else if (chrome::GetTotalBrowserCount() == 0) {
[self windowChangedToProfile:
g_browser_process->profile_manager()->GetLastUsedProfile()];
}
}
- (void)activeSpaceDidChange:(NSNotification*)notify {
if (reopenTime_.is_null() ||
![NSApp isActive] ||
(base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
kWorkspaceChangeTimeoutMs) {
return;
}
// The last applicationShouldHandleReopen:hasVisibleWindows: call
// happened during a space change. Now that the change has
// completed, raise browser windows.
reopenTime_ = base::TimeTicks();
std::set<NSWindow*> browserWindows;
for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
Browser* browser = *iter;
browserWindows.insert(browser->window()->GetNativeWindow());
}
if (!browserWindows.empty()) {
ui::FocusWindowSetOnCurrentSpace(browserWindows);
}
}
// Called on Lion and later when a popover (e.g. dictionary) is shown.
- (void)popoverDidShow:(NSNotification*)notify {
hasPopover_ = YES;
[self fixCloseMenuItemKeyEquivalents];
}
// Called on Lion and later when a popover (e.g. dictionary) is closed.
- (void)popoverDidClose:(NSNotification*)notify {
hasPopover_ = NO;
[self fixCloseMenuItemKeyEquivalents];
}
- (void)checkForAnyKeyWindows {
if ([NSApp keyWindow])
return;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_NO_KEY_WINDOW,
content::NotificationService::AllSources(),
content::NotificationService::NoDetails());
}
// If the auto-update interval is not set, make it 5 hours.
// Placed here for 2 reasons:
// 1) Same spot as other Pref stuff
// 2) Try and be friendly by keeping this after app launch
- (void)setUpdateCheckInterval {
#if defined(GOOGLE_CHROME_BUILD)
CFStringRef app = CFSTR("com.google.Keystone.Agent");
CFStringRef checkInterval = CFSTR("checkInterval");
CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
if (!plist) {
const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
CFPreferencesSetAppValue(checkInterval, value, app);
CFPreferencesAppSynchronize(app);
}
#endif
}
- (void)openStartupUrls {
DCHECK(startupComplete_);
[self openUrlsReplacingNTP:startupUrls_];
startupUrls_.clear();
}
- (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls {
if (urls.empty())
return;
// On Mac, the URLs are passed in via Cocoa, not command line. The Chrome
// NSApplication is created in MainMessageLoop, and then the shortcut urls
// are passed in via Apple events. At this point, the first browser is
// already loaded in PreMainMessageLoop. If we initialize NSApplication
// before PreMainMessageLoop to capture shortcut URL events, it may cause
// more problems because it relies on things created in PreMainMessageLoop
// and may break existing message loop design.
// If the browser hasn't started yet, just queue up the URLs.
if (!startupComplete_) {
startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
return;
}
// If there's only 1 tab and the tab is NTP, close this NTP tab and open all
// startup urls in new tabs, because the omnibox will stay focused if we
// load url in NTP tab.
Browser* browser = chrome::GetLastActiveBrowser();
int startupIndex = TabStripModel::kNoTab;
content::WebContents* startupContent = NULL;
if (browser && browser->tab_strip_model()->count() == 1) {
startupIndex = browser->tab_strip_model()->active_index();
startupContent = browser->tab_strip_model()->GetActiveWebContents();
}
[self openUrls:urls];
if (startupIndex != TabStripModel::kNoTab &&
startupContent->GetVisibleURL() == GURL(chrome::kChromeUINewTabURL)) {
browser->tab_strip_model()->CloseWebContentsAt(startupIndex,
TabStripModel::CLOSE_NONE);
}
}
// This is called after profiles have been loaded and preferences registered.
// It is safe to access the default profile here.
- (void)applicationDidFinishLaunching:(NSNotification*)notify {
MacStartupProfiler::GetInstance()->Profile(
MacStartupProfiler::DID_FINISH_LAUNCHING);
MacStartupProfiler::GetInstance()->RecordMetrics();
// Notify BrowserList to keep the application running so it doesn't go away
// when all the browser windows get closed.
chrome::IncrementKeepAliveCount();
[self setUpdateCheckInterval];
// Start managing the menu for app windows. This needs to be done here because
// main menu item titles are not yet initialized in awakeFromNib.
[self initAppShimMenuController];
// If enabled, keep Chrome alive when apps are open instead of quitting all
// apps.
quitWithAppsController_ = new QuitWithAppsController();
// Build up the encoding menu, the order of the items differs based on the
// current locale (see http://crbug.com/7647 for details).
// We need a valid g_browser_process to get the profile which is why we can't
// call this from awakeFromNib.
NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
NSMenu* encodingMenu = [encodingMenuItem submenu];
EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
encodingMenu);
// Instantiate the ProfileInfoCache observer so that we can get
// notified when a profile is deleted.
profileInfoCacheObserver_.reset(new AppControllerProfileObserver(
g_browser_process->profile_manager(), self));
// Since Chrome is localized to more languages than the OS, tell Cocoa which
// menu is the Help so it can add the search item to it.
[NSApp setHelpMenu:helpMenu_];
// Record the path to the (browser) app bundle; this is used by the app mode
// shim. It has to be done in FILE thread because getting the path requires
// I/O.
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&RecordLastRunAppBundlePath));
// Makes "Services" menu items available.
[self registerServicesMenuTypesTo:[notify object]];
startupComplete_ = YES;
Browser* browser =
FindLastActiveWithHostDesktopType(chrome::HOST_DESKTOP_TYPE_NATIVE);
content::WebContents* activeWebContents = nullptr;
if (browser)
activeWebContents = browser->tab_strip_model()->GetActiveWebContents();
[self updateHandoffManager:activeWebContents];
[self openStartupUrls];
PrefService* localState = g_browser_process->local_state();
if (localState) {
localPrefRegistrar_.Init(localState);
localPrefRegistrar_.Add(
prefs::kAllowFileSelectionDialogs,
base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
menuState_.get()));
}
handoff_active_url_observer_bridge_.reset(
new HandoffActiveURLObserverBridge(self));
}
// This is called after profiles have been loaded and preferences registered.
// It is safe to access the default profile here.
- (void)applicationDidBecomeActive:(NSNotification*)notify {
content::PluginService::GetInstance()->AppActivated();
}
// Helper function for populating and displaying the in progress downloads at
// exit alert panel.
- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
NSString* titleText = nil;
NSString* explanationText = nil;
NSString* waitTitle = nil;
NSString* exitTitle = nil;
// Set the dialog text based on whether or not there are multiple downloads.
if (downloadCount == 1) {
// Dialog text: warning and explanation.
titleText = l10n_util::GetNSString(
IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_TITLE);
explanationText = l10n_util::GetNSString(
IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
} else {
// Dialog text: warning and explanation.
titleText = l10n_util::GetNSString(
IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_TITLE);
explanationText = l10n_util::GetNSString(
IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
}
// Cancel download and exit button text.
exitTitle = l10n_util::GetNSString(
IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
// Wait for download button text.
waitTitle = l10n_util::GetNSString(
IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
// 'waitButton' is the default choice.
int choice = NSRunAlertPanel(titleText, @"%@",
waitTitle, exitTitle, nil, explanationText);
return choice == NSAlertDefaultReturn ? YES : NO;
}
// Check all profiles for in progress downloads, and if we find any, prompt the
// user to see if we should continue to exit (and thus cancel the downloads), or
// if we should wait.
- (BOOL)shouldQuitWithInProgressDownloads {
ProfileManager* profile_manager = g_browser_process->profile_manager();
if (!profile_manager)
return YES;
std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
for (size_t i = 0; i < profiles.size(); ++i) {
DownloadService* download_service =
DownloadServiceFactory::GetForBrowserContext(profiles[i]);
DownloadManager* download_manager =
(download_service->HasCreatedDownloadManager() ?
BrowserContext::GetDownloadManager(profiles[i]) : NULL);
if (download_manager &&
download_manager->NonMaliciousInProgressCount() > 0) {
int downloadCount = download_manager->NonMaliciousInProgressCount();
if ([self userWillWaitForInProgressDownloads:downloadCount]) {
// Create a new browser window (if necessary) and navigate to the
// downloads page if the user chooses to wait.
Browser* browser = chrome::FindBrowserWithProfile(
profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
if (!browser) {
browser = new Browser(Browser::CreateParams(
profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
browser->window()->Show();
}
DCHECK(browser);
chrome::ShowDownloads(browser);
return NO;
}
// User wants to exit.
return YES;
}
}
// No profiles or active downloads found, okay to exit.
return YES;
}
// Called to determine if we should enable the "restore tab" menu item.
// Checks with the TabRestoreService to see if there's anything there to
// restore and returns YES if so.
- (BOOL)canRestoreTab {
TabRestoreService* service =
TabRestoreServiceFactory::GetForProfile([self lastProfile]);
return service && !service->entries().empty();
}
// Called from the AppControllerProfileObserver every time a profile is deleted.
- (void)profileWasRemoved:(const base::FilePath&)profilePath {
Profile* lastProfile = [self lastProfile];
// If the lastProfile has been deleted, the profile manager has
// already loaded a new one, so the pointer needs to be updated;
// otherwise we will try to start up a browser window with a pointer
// to the old profile.
if (profilePath == lastProfile->GetPath())
lastProfile_ = g_browser_process->profile_manager()->GetLastUsedProfile();
Profile* profile =
g_browser_process->profile_manager()->GetProfile(profilePath);
auto it = profileBookmarkMenuBridgeMap_.find(profile);
if (it != profileBookmarkMenuBridgeMap_.end()) {
delete it->second;
profileBookmarkMenuBridgeMap_.erase(it);
}
}
// Returns true if there is a modal window (either window- or application-
// modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
// sheets) will not count as blocking the browser. But things like open/save
// dialogs that are window modal will block the browser.
- (BOOL)keyWindowIsModal {
if ([NSApp modalWindow])
return YES;
Browser* browser = chrome::GetLastActiveBrowser();
return browser &&
[[browser->window()->GetNativeWindow() attachedSheet]
isKindOfClass:[NSWindow class]];
}
// Called to validate menu items when there are no key windows. All the
// items we care about have been set with the |commandDispatch:| action and
// a target of FirstResponder in IB. If it's not one of those, let it
// continue up the responder chain to be handled elsewhere. We pull out the
// tag as the cross-platform constant to differentiate and dispatch the
// various commands.
- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
SEL action = [item action];
BOOL enable = NO;
if (action == @selector(commandDispatch:) ||
action == @selector(commandFromDock:)) {
NSInteger tag = [item tag];
if (menuState_ && // NULL in tests.
menuState_->SupportsCommand(tag)) {
switch (tag) {
// The File Menu commands are not automatically disabled by Cocoa when a
// dialog sheet obscures the browser window, so we disable several of
// them here. We don't need to include IDC_CLOSE_WINDOW, because
// app_controller is only activated when there are no key windows (see
// function comment).
case IDC_RESTORE_TAB:
enable = ![self keyWindowIsModal] && [self canRestoreTab];
break;
// Browser-level items that open in new tabs should not open if there's
// a window- or app-modal dialog.
case IDC_OPEN_FILE:
case IDC_NEW_TAB:
case IDC_SHOW_HISTORY:
case IDC_SHOW_BOOKMARK_MANAGER:
enable = ![self keyWindowIsModal];
break;
// Browser-level items that open in new windows.
case IDC_TASK_MANAGER:
// Allow the user to open a new window if there's a window-modal
// dialog.
enable = ![self keyWindowIsModal];
break;
case IDC_SHOW_SYNC_SETUP: {
Profile* lastProfile = [self lastProfile];
// The profile may be NULL during shutdown -- see
// http://code.google.com/p/chromium/issues/detail?id=43048 .
//
// TODO(akalin,viettrungluu): Figure out whether this method
// can be prevented from being called if lastProfile is
// NULL.
if (!lastProfile) {
LOG(WARNING)
<< "NULL lastProfile detected -- not doing anything";
break;
}
SigninManager* signin = SigninManagerFactory::GetForProfile(
lastProfile->GetOriginalProfile());
enable = signin->IsSigninAllowed() &&
![self keyWindowIsModal];
[BrowserWindowController updateSigninItem:item
shouldShow:enable
currentProfile:lastProfile];
break;
}
#if defined(GOOGLE_CHROME_BUILD)
case IDC_FEEDBACK:
enable = NO;
break;
#endif
default:
enable = menuState_->IsCommandEnabled(tag) ?
![self keyWindowIsModal] : NO;
}
}
} else if (action == @selector(terminate:)) {
enable = YES;
} else if (action == @selector(showPreferences:)) {
enable = YES;
} else if (action == @selector(orderFrontStandardAboutPanel:)) {
enable = YES;
} else if (action == @selector(commandFromDock:)) {
enable = YES;
} else if (action == @selector(toggleConfirmToQuit:)) {
[self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
enable = YES;
} else if (action == @selector(toggleDisplayMessageCenter:)) {
NSMenuItem* menuItem = static_cast<NSMenuItem*>(item);
[self updateDisplayMessageCenterPrefMenuItem:menuItem];
enable = YES;
} else if (action == @selector(executeApplication:)) {
enable = YES;
}
return enable;
}
// Called when the user picks a menu item when there are no key windows, or when
// there is no foreground browser window. Calls through to the browser object to
// execute the command. This assumes that the command is supported and doesn't
// check, otherwise it should have been disabled in the UI in
// |-validateUserInterfaceItem:|.
- (void)commandDispatch:(id)sender {
Profile* lastProfile = [self safeLastProfileForNewWindows];
// Handle the case where we're dispatching a command from a sender that's in a
// browser window. This means that the command came from a background window
// and is getting here because the foreground window is not a browser window.
if ([sender respondsToSelector:@selector(window)]) {
id delegate = [[sender window] windowController];
if ([delegate isKindOfClass:[BrowserWindowController class]]) {
[delegate commandDispatch:sender];
return;
}
}
// Ignore commands during session restore's browser creation. It uses a
// nested message loop and commands dispatched during this operation cause
// havoc.
if (SessionRestore::IsRestoring(lastProfile) &&
base::MessageLoop::current()->IsNested())
return;
NSInteger tag = [sender tag];
// If there are no browser windows, and we are trying to open a browser
// for a locked profile, we have to show the User Manager instead as the
// locked profile needs authentication.
if (IsProfileSignedOut(lastProfile)) {
UserManager::Show(base::FilePath(),
profiles::USER_MANAGER_NO_TUTORIAL,
profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
return;
}
switch (tag) {
case IDC_NEW_TAB:
// Create a new tab in an existing browser window (which we activate) if
// possible.
if (Browser* browser = ActivateBrowser(lastProfile)) {
chrome::ExecuteCommand(browser, IDC_NEW_TAB);
break;
}
// Else fall through to create new window.
case IDC_NEW_WINDOW:
CreateBrowser(lastProfile);
break;
case IDC_FOCUS_LOCATION:
chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
IDC_FOCUS_LOCATION);
break;
case IDC_FOCUS_SEARCH:
chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
IDC_FOCUS_SEARCH);
break;
case IDC_NEW_INCOGNITO_WINDOW:
CreateBrowser(lastProfile->GetOffTheRecordProfile());
break;
case IDC_RESTORE_TAB:
// There is only the native desktop on Mac.
chrome::OpenWindowWithRestoredTabs(lastProfile,
chrome::HOST_DESKTOP_TYPE_NATIVE);
break;
case IDC_OPEN_FILE:
chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
break;
case IDC_CLEAR_BROWSING_DATA: {
// There may not be a browser open, so use the default profile.
if (Browser* browser = ActivateBrowser(lastProfile)) {
chrome::ShowClearBrowsingDataDialog(browser);
} else {
chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
}
break;
}
case IDC_IMPORT_SETTINGS: {
if (Browser* browser = ActivateBrowser(lastProfile)) {
chrome::ShowImportDialog(browser);
} else {
chrome::OpenImportSettingsDialogWindow(lastProfile);
}
break;
}
case IDC_SHOW_BOOKMARK_MANAGER:
content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
if (Browser* browser = ActivateBrowser(lastProfile)) {
chrome::ShowBookmarkManager(browser);
} else {
// No browser window, so create one for the bookmark manager tab.
chrome::OpenBookmarkManagerWindow(lastProfile);
}
break;
case IDC_SHOW_HISTORY:
if (Browser* browser = ActivateBrowser(lastProfile))
chrome::ShowHistory(browser);
else
chrome::OpenHistoryWindow(lastProfile);
break;
case IDC_SHOW_DOWNLOADS:
if (Browser* browser = ActivateBrowser(lastProfile))
chrome::ShowDownloads(browser);
else
chrome::OpenDownloadsWindow(lastProfile);
break;
case IDC_MANAGE_EXTENSIONS:
if (Browser* browser = ActivateBrowser(lastProfile))
chrome::ShowExtensions(browser, std::string());
else
chrome::OpenExtensionsWindow(lastProfile);
break;
case IDC_HELP_PAGE_VIA_MENU:
if (Browser* browser = ActivateBrowser(lastProfile))
chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
else
chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
break;
case IDC_SHOW_SYNC_SETUP:
if (Browser* browser = ActivateBrowser(lastProfile)) {
chrome::ShowBrowserSignin(browser, signin_metrics::SOURCE_MENU);
} else {
chrome::OpenSyncSetupWindow(lastProfile, signin_metrics::SOURCE_MENU);
}
break;
case IDC_TASK_MANAGER:
chrome::OpenTaskManager(NULL);
break;
case IDC_OPTIONS:
[self showPreferences:sender];
break;
}
}
// Run a (background) application in a new tab.
- (void)executeApplication:(id)sender {
NSInteger tag = [sender tag];
Profile* profile = [self lastProfile];
DCHECK(profile);
BackgroundApplicationListModel applications(profile);
DCHECK(tag >= 0 &&
tag < static_cast<int>(applications.size()));
const extensions::Extension* extension = applications.GetExtension(tag);
BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
}
// Same as |-commandDispatch:|, but executes commands using a disposition
// determined by the key flags. This will get called in the case where the
// frontmost window is not a browser window, and the user has command-clicked
// a button in a background browser window whose action is
// |-commandDispatchUsingKeyModifiers:|
- (void)commandDispatchUsingKeyModifiers:(id)sender {
DCHECK(sender);
if ([sender respondsToSelector:@selector(window)]) {
id delegate = [[sender window] windowController];
if ([delegate isKindOfClass:[BrowserWindowController class]]) {
[delegate commandDispatchUsingKeyModifiers:sender];
}
}
}
// NSApplication delegate method called when someone clicks on the dock icon.
// To match standard mac behavior, we should open a new window if there are no
// browser windows.
- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
hasVisibleWindows:(BOOL)hasVisibleWindows {
// If the browser is currently trying to quit, don't do anything and return NO
// to prevent AppKit from doing anything.
// TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
if (browser_shutdown::IsTryingToQuit())
return NO;
// Bring all browser windows to the front. Specifically, this brings them in
// front of any app windows. FocusWindowSet will also unminimize the most
// recently minimized window if no windows in the set are visible.
// If there are any, return here. Otherwise, the windows are panels or
// notifications so we still need to open a new window.
if (hasVisibleWindows) {
std::set<NSWindow*> browserWindows;
for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
Browser* browser = *iter;
// When focusing Chrome, don't focus any browser windows associated with
// a currently running app shim, so ignore them.
if (browser && browser->is_app()) {
extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(browser->profile());
const extensions::Extension* extension = registry->GetExtensionById(
web_app::GetExtensionIdFromApplicationName(browser->app_name()),
extensions::ExtensionRegistry::ENABLED);
if (extension && extension->is_hosted_app())
continue;
}
browserWindows.insert(browser->window()->GetNativeWindow());
}
if (!browserWindows.empty()) {
NSWindow* keyWindow = [NSApp keyWindow];
if (keyWindow && ![keyWindow isOnActiveSpace]) {
// The key window is not on the active space. We must be mid-animation
// for a space transition triggered by the dock. Delay the call to
// |ui::FocusWindowSet| until the transition completes. Otherwise, the
// wrong space's windows get raised, resulting in an off-screen key
// window. It does not work to |ui::FocusWindowSet| twice, once here
// and once in |activeSpaceDidChange:|, as that appears to break when
// the omnibox is focused.
//
// This check relies on OS X setting the key window to a window on the
// target space before calling this method.
//
// See http://crbug.com/309656.
reopenTime_ = base::TimeTicks::Now();
} else {
ui::FocusWindowSetOnCurrentSpace(browserWindows);
}
// Return NO; we've done (or soon will do) the deminiaturize, so
// AppKit shouldn't do anything.
return NO;
}
}
// If launched as a hidden login item (due to installation of a persistent app
// or by the user, for example in System Preferences->Accounts->Login Items),
// allow session to be restored first time the user clicks on a Dock icon.
// Normally, it'd just open a new empty page.
{
static BOOL doneOnce = NO;
BOOL attemptRestore = apps::AppShimHandler::ShouldRestoreSession() ||
(!doneOnce && base::mac::WasLaunchedAsHiddenLoginItem());
doneOnce = YES;
if (attemptRestore) {
SessionService* sessionService =
SessionServiceFactory::GetForProfileForSessionRestore(
[self lastProfile]);
if (sessionService &&
sessionService->RestoreIfNecessary(std::vector<GURL>()))
return NO;
}
}
// Otherwise open a new window.
// If the last profile was locked, we have to open the User Manager, as the
// profile requires authentication. Similarly, because guest mode is
// implemented as forced incognito, we can't open a new guest browser either,
// so we have to show the User Manager as well.
Profile* lastProfile = [self lastProfile];
if (lastProfile->IsGuestSession() || IsProfileSignedOut(lastProfile)) {
UserManager::Show(base::FilePath(),
profiles::USER_MANAGER_NO_TUTORIAL,
profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
} else {
CreateBrowser(lastProfile);
}
// We've handled the reopen event, so return NO to tell AppKit not
// to do anything.
return NO;
}
- (void)initMenuState {
menuState_.reset(new CommandUpdater(NULL));
menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
#if defined(GOOGLE_CHROME_BUILD)
menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
#endif
menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
}
// Conditionally adds the Profile menu to the main menu bar.
- (void)initProfileMenu {
NSMenu* mainMenu = [NSApp mainMenu];
NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
if (!profiles::IsMultipleProfilesEnabled()) {
[mainMenu removeItem:profileMenu];
return;
}
// The controller will unhide the menu if necessary.
[profileMenu setHidden:YES];
profileMenuController_.reset(
[[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
}
// The Confirm to Quit preference is atypical in that the preference lives in
// the app menu right above the Quit menu item. This method will refresh the
// display of that item depending on the preference state.
- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
// Format the string so that the correct key equivalent is displayed.
NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
base::SysNSStringToUTF16(acceleratorString));
[item setTitle:title];
const PrefService* prefService = g_browser_process->local_state();
bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
[item setState:enabled ? NSOnState : NSOffState];
}
- (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item {
const PrefService* prefService = g_browser_process->local_state();
bool enabled = prefService->GetBoolean(prefs::kMessageCenterShowIcon);
// The item should be checked if "show icon" is false, since the text reads
// "Hide notification center icon."
[item setState:enabled ? NSOffState : NSOnState];
}
- (void)registerServicesMenuTypesTo:(NSApplication*)app {
// Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
// handles requests from services.
NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
[app registerServicesMenuSendTypes:types returnTypes:types];
}
- (Profile*)lastProfile {
// Return the profile of the last-used BrowserWindowController, if available.
if (lastProfile_)
return lastProfile_;
// On first launch, use the logic that ChromeBrowserMain uses to determine
// the initial profile.
ProfileManager* profile_manager = g_browser_process->profile_manager();
if (!profile_manager)
return NULL;
return profile_manager->GetProfile(
GetStartupProfilePath(profile_manager->user_data_dir(),
*base::CommandLine::ForCurrentProcess()));
}
- (Profile*)safeLastProfileForNewWindows {
Profile* profile = [self lastProfile];
// Guest sessions must always be OffTheRecord. Use that when opening windows.
if (profile->IsGuestSession())
return profile->GetOffTheRecordProfile();
return profile;
}
// Returns true if a browser window may be opened for the last active profile.
- (bool)canOpenNewBrowser {
Profile* profile = [self safeLastProfileForNewWindows];
const PrefService* prefs = g_browser_process->local_state();
return !profile->IsGuestSession() ||
prefs->GetBoolean(prefs::kBrowserGuestModeEnabled);
}
// Various methods to open URLs that we get in a native fashion. We use
// StartupBrowserCreator here because on the other platforms, URLs to open come
// through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
// to bottleneck the openings through that for uniform handling.
- (void)openUrls:(const std::vector<GURL>&)urls {
if (!startupComplete_) {
startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
return;
}
Browser* browser = chrome::GetLastActiveBrowser();
// if no browser window exists then create one with no tabs to be filled in
if (!browser) {
browser = new Browser(Browser::CreateParams(
[self lastProfile], chrome::HOST_DESKTOP_TYPE_NATIVE));
browser->window()->Show();
}
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
launch.OpenURLsInBrowser(browser, false, urls, browser->host_desktop_type());
}
- (void)getUrl:(NSAppleEventDescriptor*)event
withReply:(NSAppleEventDescriptor*)reply {
NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
stringValue];
GURL gurl(base::SysNSStringToUTF8(urlStr));
std::vector<GURL> gurlVector;
gurlVector.push_back(gurl);
[self openUrlsReplacingNTP:gurlVector];
}
- (void)application:(NSApplication*)sender
openFiles:(NSArray*)filenames {
std::vector<GURL> gurlVector;
for (NSString* file in filenames) {
GURL gurl =
net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
gurlVector.push_back(gurl);
}
if (!gurlVector.empty())
[self openUrlsReplacingNTP:gurlVector];
else
NOTREACHED() << "Nothing to open!";
[sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
}
// Show the preferences window, or bring it to the front if it's already
// visible.
- (IBAction)showPreferences:(id)sender {
if (Browser* browser = ActivateBrowser([self lastProfile])) {
// Show options tab in the active browser window.
chrome::ShowSettings(browser);
} else if ([self canOpenNewBrowser]) {
// No browser window, so create one for the options tab.
chrome::OpenOptionsWindow([self safeLastProfileForNewWindows]);
} else {
// No way to create a browser, default to the User Manager.
UserManager::Show(base::FilePath(),
profiles::USER_MANAGER_NO_TUTORIAL,
profiles::USER_MANAGER_SELECT_PROFILE_CHROME_SETTINGS);
}
}
- (IBAction)orderFrontStandardAboutPanel:(id)sender {
if (Browser* browser = ActivateBrowser([self lastProfile])) {
chrome::ShowAboutChrome(browser);
} else if ([self canOpenNewBrowser]) {
// No browser window, so create one for the options tab.
chrome::OpenAboutWindow([self safeLastProfileForNewWindows]);
} else {
// No way to create a browser, default to the User Manager.
UserManager::Show(base::FilePath(),
profiles::USER_MANAGER_NO_TUTORIAL,
profiles::USER_MANAGER_SELECT_PROFILE_ABOUT_CHROME);
}
}
- (IBAction)toggleConfirmToQuit:(id)sender {
PrefService* prefService = g_browser_process->local_state();
bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
}
- (IBAction)toggleDisplayMessageCenter:(id)sender {
PrefService* prefService = g_browser_process->local_state();
bool enabled = prefService->GetBoolean(prefs::kMessageCenterShowIcon);
prefService->SetBoolean(prefs::kMessageCenterShowIcon, !enabled);
}
// Explicitly bring to the foreground when creating new windows from the dock.
- (void)commandFromDock:(id)sender {
[NSApp activateIgnoringOtherApps:YES];
[self commandDispatch:sender];
}
- (NSMenu*)applicationDockMenu:(NSApplication*)sender {
NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
Profile* profile = [self lastProfile];
BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
atOffset:0
fromDock:YES];
if (profilesAdded)
[dockMenu addItem:[NSMenuItem separatorItem]];
NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
base::scoped_nsobject<NSMenuItem> item(
[[NSMenuItem alloc] initWithTitle:titleStr
action:@selector(commandFromDock:)
keyEquivalent:@""]);
[item setTarget:self];
[item setTag:IDC_NEW_WINDOW];
[item setEnabled:[self validateUserInterfaceItem:item]];
[dockMenu addItem:item];
// |profile| can be NULL during unit tests.
if (!profile ||
IncognitoModePrefs::GetAvailability(profile->GetPrefs()) !=
IncognitoModePrefs::DISABLED) {
titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
item.reset(
[[NSMenuItem alloc] initWithTitle:titleStr
action:@selector(commandFromDock:)
keyEquivalent:@""]);
[item setTarget:self];
[item setTag:IDC_NEW_INCOGNITO_WINDOW];
[item setEnabled:[self validateUserInterfaceItem:item]];
[dockMenu addItem:item];
}
// TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
// tests which use the mock in place of the profile-initialized model.
// Avoid breaking unit tests which have no profile.
if (profile) {
BackgroundApplicationListModel applications(profile);
if (applications.size()) {
int position = 0;
NSString* menuStr =
l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
base::scoped_nsobject<NSMenu> appMenu(
[[NSMenu alloc] initWithTitle:menuStr]);
for (extensions::ExtensionList::const_iterator cursor =
applications.begin();
cursor != applications.end();
++cursor, ++position) {
DCHECK_EQ(applications.GetPosition(cursor->get()), position);
NSString* itemStr =
base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
base::scoped_nsobject<NSMenuItem> appItem(
[[NSMenuItem alloc] initWithTitle:itemStr
action:@selector(executeApplication:)
keyEquivalent:@""]);
[appItem setTarget:self];
[appItem setTag:position];
[appMenu addItem:appItem];
}
}
}
return dockMenu;
}
- (const std::vector<GURL>&)startupUrls {
return startupUrls_;
}
- (BookmarkMenuBridge*)bookmarkMenuBridge {
return bookmarkMenuBridge_;
}
- (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
workAreaChangeObservers_.AddObserver(observer);
}
- (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
workAreaChangeObservers_.RemoveObserver(observer);
}
- (void)initAppShimMenuController {
if (!appShimMenuController_)
appShimMenuController_.reset([[AppShimMenuController alloc] init]);
}
- (void)windowChangedToProfile:(Profile*)profile {
if (lastProfile_ == profile)
return;
// Before tearing down the menu controller bridges, return the history menu to
// its initial state.
if (historyMenuBridge_)
historyMenuBridge_->ResetMenu();
// Rebuild the menus with the new profile.
lastProfile_ = profile;
auto it = profileBookmarkMenuBridgeMap_.find(profile);
if (it == profileBookmarkMenuBridgeMap_.end()) {
base::scoped_nsobject<NSMenu> submenu(
[[[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu] copy]);
bookmarkMenuBridge_ = new BookmarkMenuBridge(lastProfile_, submenu);
profileBookmarkMenuBridgeMap_[profile] = bookmarkMenuBridge_;
} else {
bookmarkMenuBridge_ = it->second;
}
[[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] setSubmenu:
bookmarkMenuBridge_->BookmarkMenu()];
// No need to |BuildMenu| here. It is done lazily upon menu access.
historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
historyMenuBridge_->BuildMenu();
chrome::BrowserCommandController::
UpdateSharedCommandsForIncognitoAvailability(
menuState_.get(), lastProfile_);
profilePrefRegistrar_.reset(new PrefChangeRegistrar());
profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
profilePrefRegistrar_->Add(
prefs::kIncognitoModeAvailability,
base::Bind(&chrome::BrowserCommandController::
UpdateSharedCommandsForIncognitoAvailability,
menuState_.get(),
lastProfile_));
}
- (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
// During this callback the working area is not always already updated. Defer.
[self performSelector:@selector(delayedScreenParametersUpdate)
withObject:nil
afterDelay:0];
}
- (void)delayedScreenParametersUpdate {
FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
WorkAreaChanged());
}
- (BOOL)application:(NSApplication*)application
willContinueUserActivityWithType:(NSString*)userActivityType {
return [userActivityType isEqualToString:NSUserActivityTypeBrowsingWeb];
}
- (BOOL)application:(NSApplication*)application
continueUserActivity:(NSUserActivity*)userActivity
restorationHandler:(void (^)(NSArray*))restorationHandler {
if (![userActivity.activityType
isEqualToString:NSUserActivityTypeBrowsingWeb]) {
return NO;
}
NSString* originString = base::mac::ObjCCast<NSString>(
[userActivity.userInfo objectForKey:handoff::kOriginKey]);
handoff::Origin origin = handoff::OriginFromString(originString);
UMA_HISTOGRAM_ENUMERATION(
"OSX.Handoff.Origin", origin, handoff::ORIGIN_COUNT);
NSURL* url = userActivity.webpageURL;
if (!url)
return NO;
GURL gurl(base::SysNSStringToUTF8([url absoluteString]));
std::vector<GURL> gurlVector;
gurlVector.push_back(gurl);
[self openUrlsReplacingNTP:gurlVector];
return YES;
}
- (void)application:(NSApplication*)application
didFailToContinueUserActivityWithType:(NSString*)userActivityType
error:(NSError*)error {
}
#pragma mark - Handoff Manager
- (BOOL)shouldUseHandoff {
return base::mac::IsOSYosemiteOrLater();
}
- (void)passURLToHandoffManager:(const GURL&)handoffURL {
[handoffManager_ updateActiveURL:handoffURL];
}
- (void)updateHandoffManager:(content::WebContents*)webContents {
if (![self shouldUseHandoff])
return;
if (!handoffManager_)
handoffManager_.reset([[HandoffManager alloc] init]);
GURL handoffURL = [self handoffURLFromWebContents:webContents];
[self passURLToHandoffManager:handoffURL];
}
- (GURL)handoffURLFromWebContents:(content::WebContents*)webContents {
if (!webContents)
return GURL();
Profile* profile =
Profile::FromBrowserContext(webContents->GetBrowserContext());
if (!profile)
return GURL();
// Handoff is not allowed from an incognito profile. To err on the safe side,
// also disallow Handoff from a guest profile.
if (profile->GetProfileType() != Profile::REGULAR_PROFILE)
return GURL();
if (!webContents)
return GURL();
return webContents->GetVisibleURL();
}
#pragma mark - HandoffActiveURLObserverBridgeDelegate
- (void)handoffActiveURLChanged:(content::WebContents*)webContents {
[self updateHandoffManager:webContents];
}
@end // @implementation AppController
//---------------------------------------------------------------------------
namespace app_controller_mac {
bool IsOpeningNewWindow() {
return g_is_opening_new_window;
}
} // namespace app_controller_mac
|