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>
8 #include <sys/sysctl.h>
10 #include "base/command_line.h"
11 #include "base/files/file_path.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/metrics/histogram.h"
16 #include "base/path_service.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/breakpad_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 // This is one enum instead of two so that the values can be correlated in a
40 // Older than any expected cat.
41 SABER_TOOTHED_CAT_32 = 0,
47 LION_32, // Unexpected, Lion requires a 64-bit CPU.
49 MOUNTAIN_LION_32, // Unexpected, Mountain Lion requires a 64-bit CPU.
51 MAVERICKS_32, // Unexpected, Mavericks requires a 64-bit CPU.
54 // DON'T add new constants here. It's important to keep the constant values,
55 // um, constant. Add new constants at the bottom.
57 // What if the bitsiness of the CPU can't be determined?
58 SABER_TOOTHED_CAT_DUNNO,
65 YOSEMITE_32, // Unexpected, Yosemite requires a 64-bit CPU.
69 // Newer than any known cat.
70 FUTURE_CAT_32, // Unexpected, it's unlikely Apple will un-obsolete old CPUs.
74 // As new versions of Mac OS X are released with sillier and sillier names,
75 // rename the FUTURE_CAT enum values to match those names, and re-create
76 // FUTURE_CAT_[32|64|DUNNO] here.
81 CatSixtyFour CatSixtyFourValue() {
82 #if defined(ARCH_CPU_64_BITS)
83 // If 64-bit code is running, then it's established that this CPU can run
84 // 64-bit code, and no further inquiry is necessary.
86 bool cpu64_known = true;
88 // Check a sysctl conveniently provided by the kernel that identifies
89 // whether the CPU supports 64-bit operation. Note that this tests the
90 // actual hardware capabilities, not the bitsiness of the running process,
91 // and not the bitsiness of the running kernel. The value thus determines
92 // whether the CPU is capable of running 64-bit programs (in the presence of
93 // proper OS runtime support) without regard to whether the current program
94 // is 64-bit (it may not be) or whether the current kernel is (the kernel
95 // can launch cross-bitted user-space tasks).
98 size_t len = sizeof(cpu64);
99 const char kSysctlName[] = "hw.cpu64bit_capable";
100 bool cpu64_known = sysctlbyname(kSysctlName, &cpu64, &len, NULL, 0) == 0;
102 PLOG(WARNING) << "sysctlbyname(\"" << kSysctlName << "\")";
106 if (base::mac::IsOSSnowLeopard()) {
107 return cpu64_known ? (cpu64 ? SNOW_LEOPARD_64 : SNOW_LEOPARD_32) :
110 if (base::mac::IsOSLion()) {
111 return cpu64_known ? (cpu64 ? LION_64 : LION_32) :
114 if (base::mac::IsOSMountainLion()) {
115 return cpu64_known ? (cpu64 ? MOUNTAIN_LION_64 : MOUNTAIN_LION_32) :
118 if (base::mac::IsOSMavericks()) {
119 return cpu64_known ? (cpu64 ? MAVERICKS_64 : MAVERICKS_32) :
122 if (base::mac::IsOSYosemite()) {
123 return cpu64_known ? (cpu64 ? YOSEMITE_64 : YOSEMITE_32) :
126 if (base::mac::IsOSLaterThanYosemite_DontCallThis()) {
127 return cpu64_known ? (cpu64 ? FUTURE_CAT_64 : FUTURE_CAT_32) :
131 // If it's not any of the expected OS versions or later than them, it must
133 return cpu64_known ? (cpu64 ? SABER_TOOTHED_CAT_64 : SABER_TOOTHED_CAT_32) :
134 SABER_TOOTHED_CAT_DUNNO;
137 void RecordCatSixtyFour() {
138 CatSixtyFour cat_sixty_four = CatSixtyFourValue();
140 // Set this higher than the highest value in the CatSixtyFour enum to provide
141 // some headroom and then leave it alone. See UMA_HISTOGRAM_ENUMERATION in
142 // base/metrics/histogram.h.
143 const int kMaxCatsAndSixtyFours = 32;
144 static_assert(kMaxCatsAndSixtyFours >= CAT_SIXTY_FOUR_MAX,
145 "kMaxCatsAndSixtyFours is too large");
147 UMA_HISTOGRAM_ENUMERATION("OSX.CatSixtyFour",
149 kMaxCatsAndSixtyFours);
154 // ChromeBrowserMainPartsMac ---------------------------------------------------
156 ChromeBrowserMainPartsMac::ChromeBrowserMainPartsMac(
157 const content::MainFunctionParams& parameters)
158 : ChromeBrowserMainPartsPosix(parameters) {
161 ChromeBrowserMainPartsMac::~ChromeBrowserMainPartsMac() {
164 void ChromeBrowserMainPartsMac::PreEarlyInitialization() {
165 ChromeBrowserMainPartsPosix::PreEarlyInitialization();
167 if (base::mac::WasLaunchedAsLoginItemRestoreState()) {
168 base::CommandLine* singleton_command_line =
169 base::CommandLine::ForCurrentProcess();
170 singleton_command_line->AppendSwitch(switches::kRestoreLastSession);
171 } else if (base::mac::WasLaunchedAsHiddenLoginItem()) {
172 base::CommandLine* singleton_command_line =
173 base::CommandLine::ForCurrentProcess();
174 singleton_command_line->AppendSwitch(switches::kNoStartupWindow);
177 RecordCatSixtyFour();
180 void ChromeBrowserMainPartsMac::PreMainMessageLoopStart() {
181 MacStartupProfiler::GetInstance()->Profile(
182 MacStartupProfiler::PRE_MAIN_MESSAGE_LOOP_START);
183 ChromeBrowserMainPartsPosix::PreMainMessageLoopStart();
185 // Tell Cocoa to finish its initialization, which we want to do manually
186 // instead of calling NSApplicationMain(). The primary reason is that NSAM()
187 // never returns, which would leave all the objects currently on the stack
188 // in scoped_ptrs hanging and never cleaned up. We then load the main nib
189 // directly. The main event loop is run from common code using the
190 // MessageLoop API, which works out ok for us because it's a wrapper around
193 // Initialize NSApplication using the custom subclass.
194 chrome_browser_application_mac::RegisterBrowserCrApp();
196 // If ui_task is not NULL, the app is actually a browser_test.
197 if (!parameters().ui_task) {
198 // The browser process only wants to support the language Cocoa will use,
199 // so force the app locale to be overriden with that value.
200 l10n_util::OverrideLocaleWithCocoaLocale();
203 // Before we load the nib, we need to start up the resource bundle so we
204 // have the strings avaiable for localization.
205 // TODO(markusheintz): Read preference pref::kApplicationLocale in order
206 // to enforce the application locale.
207 const std::string loaded_locale =
208 ui::ResourceBundle::InitSharedInstanceWithLocale(
209 std::string(), NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
210 CHECK(!loaded_locale.empty()) << "Default locale could not be found";
212 base::FilePath resources_pack_path;
213 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
214 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
215 resources_pack_path, ui::SCALE_FACTOR_NONE);
217 // This is a no-op if the KeystoneRegistration framework is not present.
218 // The framework is only distributed with branded Google Chrome builds.
219 [[KeystoneGlue defaultKeystoneGlue] registerWithKeystone];
221 // Disk image installation is sort of a first-run task, so it shares the
222 // no first run switches.
224 // This needs to be done after the resource bundle is initialized (for
225 // access to localizations in the UI) and after Keystone is initialized
226 // (because the installation may need to promote Keystone) but before the
227 // app controller is set up (and thus before MainMenu.nib is loaded, because
228 // the app controller assumes that a browser has been set up and will crash
229 // upon receipt of certain notifications if no browser exists), before
230 // anyone tries doing anything silly like firing off an import job, and
231 // before anything creating preferences like Local State in order for the
232 // relaunched installed application to still consider itself as first-run.
233 if (!first_run::IsFirstRunSuppressed(parsed_command_line())) {
234 if (MaybeInstallFromDiskImage()) {
235 // The application was installed and the installed copy has been
236 // launched. This process is now obsolete. Exit.
241 // Now load the nib (from the right bundle).
242 base::scoped_nsobject<NSNib> nib(
243 [[NSNib alloc] initWithNibNamed:@"MainMenu"
244 bundle:base::mac::FrameworkBundle()]);
245 // TODO(viettrungluu): crbug.com/20504 - This currently leaks, so if you
246 // change this, you'll probably need to change the Valgrind suppression.
247 [nib instantiateNibWithOwner:NSApp topLevelObjects:nil];
248 // Make sure the app controller has been created.
249 DCHECK([NSApp delegate]);
251 [[NSUserDefaults standardUserDefaults] registerDefaults:@{
252 // Prevent Cocoa from turning command-line arguments into
253 // |-application:openFiles:|, since we already handle them directly.
254 // @"NO" looks like a mistake, but the value really is supposed to be a
256 @"NSTreatUnknownArgumentsAsOpen": @"NO",
257 // CoreAnimation has poor performance and CoreAnimation and
258 // non-CoreAnimation exhibit window flickering when layers are not hosted
259 // in the window server, which is the default when not not using the
261 // TODO: Remove this when we build with the 10.9 SDK.
262 @"NSWindowHostsLayersInWindowServer":
263 @(base::mac::IsOSMavericksOrLater()),
264 // This setting prevents views from ditching their layers when the view
265 // gets removed from the view hierarchy. It defaults to YES for
266 // applications linked against an OSX 10.8+ SDK. In Yosemite, failing to
267 // set this to YES causes an AppKit crash. http://crbug.com/428977
268 // TODO(erikchen): Remove this when we build with an OSX 10.8+ SDK.
269 @"NSViewKeepLayersAround": @(YES)
273 void ChromeBrowserMainPartsMac::PostMainMessageLoopStart() {
274 MacStartupProfiler::GetInstance()->Profile(
275 MacStartupProfiler::POST_MAIN_MESSAGE_LOOP_START);
276 ChromeBrowserMainPartsPosix::PostMainMessageLoopStart();
279 void ChromeBrowserMainPartsMac::PreProfileInit() {
280 MacStartupProfiler::GetInstance()->Profile(
281 MacStartupProfiler::PRE_PROFILE_INIT);
282 ChromeBrowserMainPartsPosix::PreProfileInit();
284 // This is called here so that the app shim socket is only created after
285 // taking the singleton lock.
286 g_browser_process->platform_part()->app_shim_host_manager()->Init();
287 AppListService::InitAll(NULL,
288 GetStartupProfilePath(user_data_dir(), parsed_command_line()));
291 void ChromeBrowserMainPartsMac::PostProfileInit() {
292 MacStartupProfiler::GetInstance()->Profile(
293 MacStartupProfiler::POST_PROFILE_INIT);
294 ChromeBrowserMainPartsPosix::PostProfileInit();
295 g_browser_process->metrics_service()->RecordBreakpadRegistration(
296 breakpad::IsCrashReporterEnabled());
299 void ChromeBrowserMainPartsMac::DidEndMainMessageLoop() {
300 AppController* appController = [NSApp delegate];
301 [appController didEndMainMessageLoop];