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.
4
5#include "chrome/browser/chrome_browser_main_mac.h"
6
7#import <Cocoa/Cocoa.h>
8#include <sys/sysctl.h>
9
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"
34
35namespace {
36
37// This is one enum instead of two so that the values can be correlated in a
38// histogram.
39enum CatSixtyFour {
40  // Older than any expected cat.
41  SABER_TOOTHED_CAT_32 = 0,
42  SABER_TOOTHED_CAT_64,
43
44  // Known cats.
45  SNOW_LEOPARD_32,
46  SNOW_LEOPARD_64,
47  LION_32,  // Unexpected, Lion requires a 64-bit CPU.
48  LION_64,
49  MOUNTAIN_LION_32,  // Unexpected, Mountain Lion requires a 64-bit CPU.
50  MOUNTAIN_LION_64,
51  MAVERICKS_32,  // Unexpected, Mavericks requires a 64-bit CPU.
52  MAVERICKS_64,
53
54  // DON'T add new constants here. It's important to keep the constant values,
55  // um, constant. Add new constants at the bottom.
56
57  // What if the bitsiness of the CPU can't be determined?
58  SABER_TOOTHED_CAT_DUNNO,
59  SNOW_LEOPARD_DUNNO,
60  LION_DUNNO,
61  MOUNTAIN_LION_DUNNO,
62  MAVERICKS_DUNNO,
63
64  // More known cats.
65  YOSEMITE_32,  // Unexpected, Yosemite requires a 64-bit CPU.
66  YOSEMITE_64,
67  YOSEMITE_DUNNO,
68
69  // Newer than any known cat.
70  FUTURE_CAT_32,  // Unexpected, it's unlikely Apple will un-obsolete old CPUs.
71  FUTURE_CAT_64,
72  FUTURE_CAT_DUNNO,
73
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.
77
78  CAT_SIXTY_FOUR_MAX
79};
80
81CatSixtyFour 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.
85  int cpu64 = 1;
86  bool cpu64_known = true;
87#else
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).
96
97  int cpu64;
98  size_t len = sizeof(cpu64);
99  const char kSysctlName[] = "hw.cpu64bit_capable";
100  bool cpu64_known = sysctlbyname(kSysctlName, &cpu64, &len, NULL, 0) == 0;
101  if (!cpu64_known) {
102    PLOG(WARNING) << "sysctlbyname(\"" << kSysctlName << "\")";
103  }
104#endif
105
106  if (base::mac::IsOSSnowLeopard()) {
107    return cpu64_known ? (cpu64 ? SNOW_LEOPARD_64 : SNOW_LEOPARD_32) :
108                         SNOW_LEOPARD_DUNNO;
109  }
110  if (base::mac::IsOSLion()) {
111    return cpu64_known ? (cpu64 ? LION_64 : LION_32) :
112                         LION_DUNNO;
113  }
114  if (base::mac::IsOSMountainLion()) {
115    return cpu64_known ? (cpu64 ? MOUNTAIN_LION_64 : MOUNTAIN_LION_32) :
116                         MOUNTAIN_LION_DUNNO;
117  }
118  if (base::mac::IsOSMavericks()) {
119    return cpu64_known ? (cpu64 ? MAVERICKS_64 : MAVERICKS_32) :
120                         MAVERICKS_DUNNO;
121  }
122  if (base::mac::IsOSYosemite()) {
123    return cpu64_known ? (cpu64 ? YOSEMITE_64 : YOSEMITE_32) :
124                         YOSEMITE_DUNNO;
125  }
126  if (base::mac::IsOSLaterThanYosemite_DontCallThis()) {
127    return cpu64_known ? (cpu64 ? FUTURE_CAT_64 : FUTURE_CAT_32) :
128                         FUTURE_CAT_DUNNO;
129  }
130
131  // If it's not any of the expected OS versions or later than them, it must
132  // be prehistoric.
133  return cpu64_known ? (cpu64 ? SABER_TOOTHED_CAT_64 : SABER_TOOTHED_CAT_32) :
134                       SABER_TOOTHED_CAT_DUNNO;
135}
136
137void RecordCatSixtyFour() {
138  CatSixtyFour cat_sixty_four = CatSixtyFourValue();
139
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  COMPILE_ASSERT(kMaxCatsAndSixtyFours >= CAT_SIXTY_FOUR_MAX,
145                 CatSixtyFour_enum_grew_too_large);
146
147  UMA_HISTOGRAM_ENUMERATION("OSX.CatSixtyFour",
148                            cat_sixty_four,
149                            kMaxCatsAndSixtyFours);
150}
151
152}  // namespace
153
154// ChromeBrowserMainPartsMac ---------------------------------------------------
155
156ChromeBrowserMainPartsMac::ChromeBrowserMainPartsMac(
157    const content::MainFunctionParams& parameters)
158    : ChromeBrowserMainPartsPosix(parameters) {
159}
160
161ChromeBrowserMainPartsMac::~ChromeBrowserMainPartsMac() {
162}
163
164void ChromeBrowserMainPartsMac::PreEarlyInitialization() {
165  ChromeBrowserMainPartsPosix::PreEarlyInitialization();
166
167  if (base::mac::WasLaunchedAsLoginItemRestoreState()) {
168    CommandLine* singleton_command_line = CommandLine::ForCurrentProcess();
169    singleton_command_line->AppendSwitch(switches::kRestoreLastSession);
170  } else if (base::mac::WasLaunchedAsHiddenLoginItem()) {
171    CommandLine* singleton_command_line = CommandLine::ForCurrentProcess();
172    singleton_command_line->AppendSwitch(switches::kNoStartupWindow);
173  }
174
175  RecordCatSixtyFour();
176}
177
178void ChromeBrowserMainPartsMac::PreMainMessageLoopStart() {
179  MacStartupProfiler::GetInstance()->Profile(
180      MacStartupProfiler::PRE_MAIN_MESSAGE_LOOP_START);
181  ChromeBrowserMainPartsPosix::PreMainMessageLoopStart();
182
183  // Tell Cocoa to finish its initialization, which we want to do manually
184  // instead of calling NSApplicationMain(). The primary reason is that NSAM()
185  // never returns, which would leave all the objects currently on the stack
186  // in scoped_ptrs hanging and never cleaned up. We then load the main nib
187  // directly. The main event loop is run from common code using the
188  // MessageLoop API, which works out ok for us because it's a wrapper around
189  // CFRunLoop.
190
191  // Initialize NSApplication using the custom subclass.
192  chrome_browser_application_mac::RegisterBrowserCrApp();
193
194  // If ui_task is not NULL, the app is actually a browser_test.
195  if (!parameters().ui_task) {
196    // The browser process only wants to support the language Cocoa will use,
197    // so force the app locale to be overriden with that value.
198    l10n_util::OverrideLocaleWithCocoaLocale();
199  }
200
201  // Before we load the nib, we need to start up the resource bundle so we
202  // have the strings avaiable for localization.
203  // TODO(markusheintz): Read preference pref::kApplicationLocale in order
204  // to enforce the application locale.
205  const std::string loaded_locale =
206      ui::ResourceBundle::InitSharedInstanceWithLocale(
207          std::string(), NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
208  CHECK(!loaded_locale.empty()) << "Default locale could not be found";
209
210  base::FilePath resources_pack_path;
211  PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
212  ResourceBundle::GetSharedInstance().AddDataPackFromPath(
213      resources_pack_path, ui::SCALE_FACTOR_NONE);
214
215  // This is a no-op if the KeystoneRegistration framework is not present.
216  // The framework is only distributed with branded Google Chrome builds.
217  [[KeystoneGlue defaultKeystoneGlue] registerWithKeystone];
218
219  // Disk image installation is sort of a first-run task, so it shares the
220  // no first run switches.
221  //
222  // This needs to be done after the resource bundle is initialized (for
223  // access to localizations in the UI) and after Keystone is initialized
224  // (because the installation may need to promote Keystone) but before the
225  // app controller is set up (and thus before MainMenu.nib is loaded, because
226  // the app controller assumes that a browser has been set up and will crash
227  // upon receipt of certain notifications if no browser exists), before
228  // anyone tries doing anything silly like firing off an import job, and
229  // before anything creating preferences like Local State in order for the
230  // relaunched installed application to still consider itself as first-run.
231  if (!first_run::IsFirstRunSuppressed(parsed_command_line())) {
232    if (MaybeInstallFromDiskImage()) {
233      // The application was installed and the installed copy has been
234      // launched.  This process is now obsolete.  Exit.
235      exit(0);
236    }
237  }
238
239  // Now load the nib (from the right bundle).
240  base::scoped_nsobject<NSNib> nib(
241      [[NSNib alloc] initWithNibNamed:@"MainMenu"
242                               bundle:base::mac::FrameworkBundle()]);
243  // TODO(viettrungluu): crbug.com/20504 - This currently leaks, so if you
244  // change this, you'll probably need to change the Valgrind suppression.
245  [nib instantiateNibWithOwner:NSApp topLevelObjects:nil];
246  // Make sure the app controller has been created.
247  DCHECK([NSApp delegate]);
248
249  [[NSUserDefaults standardUserDefaults] registerDefaults:@{
250      // Prevent Cocoa from turning command-line arguments into
251      // |-application:openFiles:|, since we already handle them directly.
252      // @"NO" looks like a mistake, but the value really is supposed to be a
253      // string.
254      @"NSTreatUnknownArgumentsAsOpen": @"NO",
255      // CoreAnimation has poor performance and CoreAnimation and
256      // non-CoreAnimation exhibit window flickering when layers are not hosted
257      // in the window server, which is the default when not not using the
258      // 10.9 SDK.
259      // TODO: Remove this when we build with the 10.9 SDK.
260      @"NSWindowHostsLayersInWindowServer": @(base::mac::IsOSMavericksOrLater())
261  }];
262}
263
264void ChromeBrowserMainPartsMac::PostMainMessageLoopStart() {
265  MacStartupProfiler::GetInstance()->Profile(
266      MacStartupProfiler::POST_MAIN_MESSAGE_LOOP_START);
267  ChromeBrowserMainPartsPosix::PostMainMessageLoopStart();
268}
269
270void ChromeBrowserMainPartsMac::PreProfileInit() {
271  MacStartupProfiler::GetInstance()->Profile(
272      MacStartupProfiler::PRE_PROFILE_INIT);
273  ChromeBrowserMainPartsPosix::PreProfileInit();
274  // This is called here so that the app shim socket is only created after
275  // taking the singleton lock.
276  g_browser_process->platform_part()->app_shim_host_manager()->Init();
277  AppListService::InitAll(NULL);
278}
279
280void ChromeBrowserMainPartsMac::PostProfileInit() {
281  MacStartupProfiler::GetInstance()->Profile(
282      MacStartupProfiler::POST_PROFILE_INIT);
283  ChromeBrowserMainPartsPosix::PostProfileInit();
284  g_browser_process->metrics_service()->RecordBreakpadRegistration(
285      breakpad::IsCrashReporterEnabled());
286}
287
288void ChromeBrowserMainPartsMac::DidEndMainMessageLoop() {
289  AppController* appController = [NSApp delegate];
290  [appController didEndMainMessageLoop];
291}
292