1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chrome_browser_main_mac.h"
7 #import <Cocoa/Cocoa.h>
9 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/files/file_util.h"
12 #include "base/mac/bundle_locations.h"
13 #include "base/mac/mac_util.h"
14 #include "base/mac/scoped_nsobject.h"
15 #include "base/path_service.h"
16 #include "base/thread_task_runner_handle.h"
17 #import "chrome/browser/app_controller_mac.h"
18 #include "chrome/browser/apps/app_shim/app_shim_host_manager_mac.h"
19 #include "chrome/browser/browser_process.h"
20 #import "chrome/browser/chrome_browser_application_mac.h"
21 #include "chrome/browser/mac/install_from_dmg.h"
22 #import "chrome/browser/mac/keystone_glue.h"
23 #include "chrome/browser/mac/mac_startup_profiler.h"
24 #include "chrome/browser/ui/app_list/app_list_service.h"
25 #include "chrome/common/chrome_paths.h"
26 #include "chrome/common/chrome_switches.h"
27 #include "components/crash/app/crashpad_mac.h"
28 #include "components/metrics/metrics_service.h"
29 #include "content/public/common/main_function_params.h"
30 #include "content/public/common/result_codes.h"
31 #include "ui/base/l10n/l10n_util_mac.h"
32 #include "ui/base/resource/resource_bundle.h"
33 #include "ui/base/resource/resource_handle.h"
37 // Writes an undocumented sentinel file that prevents Spotlight from indexing
38 // below a particular path in order to reap some power savings.
39 void EnsureMetadataNeverIndexFileOnFileThread(
40 const base::FilePath& user_data_dir) {
41 const char kMetadataNeverIndexFilename[] = ".metadata_never_index";
42 base::FilePath metadata_file_path =
43 user_data_dir.Append(kMetadataNeverIndexFilename);
44 if (base::PathExists(metadata_file_path))
47 if (base::WriteFile(metadata_file_path, nullptr, 0) == -1)
48 DLOG(FATAL) << "Could not write .metadata_never_index file.";
51 void EnsureMetadataNeverIndexFile(const base::FilePath& user_data_dir) {
52 content::BrowserThread::PostTask(
53 content::BrowserThread::FILE, FROM_HERE,
54 base::Bind(&EnsureMetadataNeverIndexFileOnFileThread, user_data_dir));
59 // ChromeBrowserMainPartsMac ---------------------------------------------------
61 ChromeBrowserMainPartsMac::ChromeBrowserMainPartsMac(
62 const content::MainFunctionParams& parameters)
63 : ChromeBrowserMainPartsPosix(parameters) {
66 ChromeBrowserMainPartsMac::~ChromeBrowserMainPartsMac() {
69 void ChromeBrowserMainPartsMac::PreEarlyInitialization() {
70 ChromeBrowserMainPartsPosix::PreEarlyInitialization();
72 if (base::mac::WasLaunchedAsLoginItemRestoreState()) {
73 base::CommandLine* singleton_command_line =
74 base::CommandLine::ForCurrentProcess();
75 singleton_command_line->AppendSwitch(switches::kRestoreLastSession);
76 } else if (base::mac::WasLaunchedAsHiddenLoginItem()) {
77 base::CommandLine* singleton_command_line =
78 base::CommandLine::ForCurrentProcess();
79 singleton_command_line->AppendSwitch(switches::kNoStartupWindow);
83 void ChromeBrowserMainPartsMac::PreMainMessageLoopStart() {
84 MacStartupProfiler::GetInstance()->Profile(
85 MacStartupProfiler::PRE_MAIN_MESSAGE_LOOP_START);
86 ChromeBrowserMainPartsPosix::PreMainMessageLoopStart();
88 // Tell Cocoa to finish its initialization, which we want to do manually
89 // instead of calling NSApplicationMain(). The primary reason is that NSAM()
90 // never returns, which would leave all the objects currently on the stack
91 // in scoped_ptrs hanging and never cleaned up. We then load the main nib
92 // directly. The main event loop is run from common code using the
93 // MessageLoop API, which works out ok for us because it's a wrapper around
96 // Initialize NSApplication using the custom subclass.
97 chrome_browser_application_mac::RegisterBrowserCrApp();
99 // If ui_task is not NULL, the app is actually a browser_test.
100 if (!parameters().ui_task) {
101 // The browser process only wants to support the language Cocoa will use,
102 // so force the app locale to be overriden with that value.
103 l10n_util::OverrideLocaleWithCocoaLocale();
106 // Before we load the nib, we need to start up the resource bundle so we
107 // have the strings avaiable for localization.
108 // TODO(markusheintz): Read preference pref::kApplicationLocale in order
109 // to enforce the application locale.
110 const std::string loaded_locale =
111 ui::ResourceBundle::InitSharedInstanceWithLocale(
112 std::string(), NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
113 CHECK(!loaded_locale.empty()) << "Default locale could not be found";
115 base::FilePath resources_pack_path;
116 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
117 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
118 resources_pack_path, ui::SCALE_FACTOR_NONE);
120 // This is a no-op if the KeystoneRegistration framework is not present.
121 // The framework is only distributed with branded Google Chrome builds.
122 [[KeystoneGlue defaultKeystoneGlue] registerWithKeystone];
124 // Disk image installation is sort of a first-run task, so it shares the
125 // no first run switches.
127 // This needs to be done after the resource bundle is initialized (for
128 // access to localizations in the UI) and after Keystone is initialized
129 // (because the installation may need to promote Keystone) but before the
130 // app controller is set up (and thus before MainMenu.nib is loaded, because
131 // the app controller assumes that a browser has been set up and will crash
132 // upon receipt of certain notifications if no browser exists), before
133 // anyone tries doing anything silly like firing off an import job, and
134 // before anything creating preferences like Local State in order for the
135 // relaunched installed application to still consider itself as first-run.
136 if (!first_run::IsFirstRunSuppressed(parsed_command_line())) {
137 if (MaybeInstallFromDiskImage()) {
138 // The application was installed and the installed copy has been
139 // launched. This process is now obsolete. Exit.
144 // Now load the nib (from the right bundle).
145 base::scoped_nsobject<NSNib> nib(
146 [[NSNib alloc] initWithNibNamed:@"MainMenu"
147 bundle:base::mac::FrameworkBundle()]);
148 // TODO(viettrungluu): crbug.com/20504 - This currently leaks, so if you
149 // change this, you'll probably need to change the Valgrind suppression.
150 [nib instantiateNibWithOwner:NSApp topLevelObjects:nil];
151 // Make sure the app controller has been created.
152 DCHECK([NSApp delegate]);
154 [[NSUserDefaults standardUserDefaults] registerDefaults:@{
155 // Prevent Cocoa from turning command-line arguments into
156 // |-application:openFiles:|, since we already handle them directly.
157 // @"NO" looks like a mistake, but the value really is supposed to be a
159 @"NSTreatUnknownArgumentsAsOpen": @"NO"
163 void ChromeBrowserMainPartsMac::PostMainMessageLoopStart() {
164 MacStartupProfiler::GetInstance()->Profile(
165 MacStartupProfiler::POST_MAIN_MESSAGE_LOOP_START);
166 ChromeBrowserMainPartsPosix::PostMainMessageLoopStart();
169 void ChromeBrowserMainPartsMac::PreProfileInit() {
170 MacStartupProfiler::GetInstance()->Profile(
171 MacStartupProfiler::PRE_PROFILE_INIT);
172 ChromeBrowserMainPartsPosix::PreProfileInit();
174 // This is called here so that the app shim socket is only created after
175 // taking the singleton lock.
176 g_browser_process->platform_part()->app_shim_host_manager()->Init();
177 AppListService::InitAll(NULL,
178 GetStartupProfilePath(user_data_dir(), parsed_command_line()));
181 void ChromeBrowserMainPartsMac::PostProfileInit() {
182 MacStartupProfiler::GetInstance()->Profile(
183 MacStartupProfiler::POST_PROFILE_INIT);
184 ChromeBrowserMainPartsPosix::PostProfileInit();
186 g_browser_process->metrics_service()->RecordBreakpadRegistration(
187 crash_reporter::GetUploadsEnabled());
189 // TODO(calamity): Make this gated on first_run::IsChromeFirstRun() in M45.
190 content::BrowserThread::PostAfterStartupTask(
191 FROM_HERE, base::ThreadTaskRunnerHandle::Get(),
192 base::Bind(&EnsureMetadataNeverIndexFile, user_data_dir()));
194 // Activation of KeyStone is not automatic but done in response to the
195 // counting and reporting of profiles. Make sure, assuming KeyStone
196 // is active, that it happened.
197 CHECK(![KeystoneGlue defaultKeystoneGlue] ||
198 [[KeystoneGlue defaultKeystoneGlue] isRegisteredAndActive]);
201 void ChromeBrowserMainPartsMac::DidEndMainMessageLoop() {
202 AppController* appController = [NSApp delegate];
203 [appController didEndMainMessageLoop];