Revert of Add button to add new FSP services to Files app. (patchset #8 id:140001...
[chromium-blink-merge.git] / chrome / app_shim / chrome_main_app_mode_mac.mm
blob7babb4a4c59be25a558152f0cbee4b5b917dfe87
1 // Copyright 2013 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 // On Mac, one can't make shortcuts with command-line arguments. Instead, we
6 // produce small app bundles which locate the Chromium framework and load it,
7 // passing the appropriate data. This is the entry point into the framework for
8 // those app bundles.
10 #import <Cocoa/Cocoa.h>
11 #include <vector>
13 #include "base/at_exit.h"
14 #include "base/command_line.h"
15 #include "base/files/file_path.h"
16 #include "base/files/file_util.h"
17 #include "base/logging.h"
18 #include "base/mac/bundle_locations.h"
19 #include "base/mac/foundation_util.h"
20 #include "base/mac/launch_services_util.h"
21 #include "base/mac/mac_logging.h"
22 #include "base/mac/mac_util.h"
23 #include "base/mac/scoped_nsautorelease_pool.h"
24 #include "base/mac/scoped_nsobject.h"
25 #include "base/mac/sdk_forward_declarations.h"
26 #include "base/message_loop/message_loop.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/sys_string_conversions.h"
29 #include "base/threading/thread.h"
30 #include "chrome/common/chrome_constants.h"
31 #include "chrome/common/chrome_paths.h"
32 #include "chrome/common/chrome_switches.h"
33 #include "chrome/common/mac/app_mode_common.h"
34 #include "chrome/common/mac/app_shim_messages.h"
35 #include "chrome/grit/generated_resources.h"
36 #include "ipc/ipc_channel_proxy.h"
37 #include "ipc/ipc_listener.h"
38 #include "ipc/ipc_message.h"
39 #include "ui/base/l10n/l10n_util.h"
40 #include "ui/base/resource/resource_bundle.h"
42 namespace {
44 // Timeout in seconds to wait for a reply for the initial Apple Event. Note that
45 // kAEDefaultTimeout on Mac is "about one minute" according to Apple's
46 // documentation, but is no longer supported for asynchronous Apple Events.
47 const int kPingChromeTimeoutSeconds = 60;
49 const app_mode::ChromeAppModeInfo* g_info;
50 base::Thread* g_io_thread = NULL;
52 }  // namespace
54 class AppShimController;
56 // An application delegate to catch user interactions and send the appropriate
57 // IPC messages to Chrome.
58 @interface AppShimDelegate : NSObject<NSApplicationDelegate> {
59  @private
60   AppShimController* appShimController_;  // Weak, initially NULL.
61   BOOL terminateNow_;
62   BOOL terminateRequested_;
63   std::vector<base::FilePath> filesToOpenAtStartup_;
66 // The controller is initially NULL. Setting it indicates to the delegate that
67 // the controller has finished initialization.
68 - (void)setController:(AppShimController*)controller;
70 // Gets files that were queued because the controller was not ready.
71 // Returns whether any FilePaths were added to |out|.
72 - (BOOL)getFilesToOpenAtStartup:(std::vector<base::FilePath>*)out;
74 // If the controller is ready, this sends a FocusApp with the files to open.
75 // Otherwise, this adds the files to |filesToOpenAtStartup_|.
76 // Takes an array of NSString*.
77 - (void)openFiles:(NSArray*)filename;
79 // Terminate immediately. This is necessary as we override terminate: to send
80 // a QuitApp message.
81 - (void)terminateNow;
83 @end
85 // The AppShimController is responsible for communication with the main Chrome
86 // process, and generally controls the lifetime of the app shim process.
87 class AppShimController : public IPC::Listener {
88  public:
89   AppShimController();
90   ~AppShimController() override;
92   // Called when the main Chrome process responds to the Apple Event ping that
93   // was sent, or when the ping fails (if |success| is false).
94   void OnPingChromeReply(bool success);
96   // Called |kPingChromeTimeoutSeconds| after startup, to allow a timeout on the
97   // ping event to be detected.
98   void OnPingChromeTimeout();
100   // Connects to Chrome and sends a LaunchApp message.
101   void Init();
103   // Create a channel from |socket_path| and send a LaunchApp message.
104   void CreateChannelAndSendLaunchApp(const base::FilePath& socket_path);
106   // Builds main menu bar items.
107   void SetUpMenu();
109   void SendSetAppHidden(bool hidden);
111   void SendQuitApp();
113   // Called when the app is activated, e.g. by clicking on it in the dock, by
114   // dropping a file on the dock icon, or by Cmd+Tabbing to it.
115   // Returns whether the message was sent.
116   bool SendFocusApp(apps::AppShimFocusType focus_type,
117                     const std::vector<base::FilePath>& files);
119  private:
120   // IPC::Listener implemetation.
121   bool OnMessageReceived(const IPC::Message& message) override;
122   void OnChannelError() override;
124   // If Chrome failed to launch the app, |success| will be false and the app
125   // shim process should die.
126   void OnLaunchAppDone(apps::AppShimLaunchResult result);
128   // Hide this app.
129   void OnHide();
131   // Requests user attention.
132   void OnRequestUserAttention();
133   void OnSetUserAttention(apps::AppShimAttentionType attention_type);
135   // Terminates the app shim process.
136   void Close();
138   base::FilePath user_data_dir_;
139   scoped_ptr<IPC::ChannelProxy> channel_;
140   base::scoped_nsobject<AppShimDelegate> delegate_;
141   bool launch_app_done_;
142   bool ping_chrome_reply_received_;
143   NSInteger attention_request_id_;
145   DISALLOW_COPY_AND_ASSIGN(AppShimController);
148 AppShimController::AppShimController()
149     : delegate_([[AppShimDelegate alloc] init]),
150       launch_app_done_(false),
151       ping_chrome_reply_received_(false),
152       attention_request_id_(0) {
153   // Since AppShimController is created before the main message loop starts,
154   // NSApp will not be set, so use sharedApplication.
155   [[NSApplication sharedApplication] setDelegate:delegate_];
158 AppShimController::~AppShimController() {
159   // Un-set the delegate since NSApplication does not retain it.
160   [[NSApplication sharedApplication] setDelegate:nil];
163 void AppShimController::OnPingChromeReply(bool success) {
164   ping_chrome_reply_received_ = true;
165   if (!success) {
166     [NSApp terminate:nil];
167     return;
168   }
170   Init();
173 void AppShimController::OnPingChromeTimeout() {
174   if (!ping_chrome_reply_received_)
175     [NSApp terminate:nil];
178 void AppShimController::Init() {
179   DCHECK(g_io_thread);
181   SetUpMenu();
183   // Chrome will relaunch shims when relaunching apps.
184   if (base::mac::IsOSLionOrLater())
185     [NSApp disableRelaunchOnLogin];
187   // The user_data_dir for shims actually contains the app_data_path.
188   // I.e. <user_data_dir>/<profile_dir>/Web Applications/_crx_extensionid/
189   user_data_dir_ = g_info->user_data_dir.DirName().DirName().DirName();
190   CHECK(!user_data_dir_.empty());
192   base::FilePath symlink_path =
193       user_data_dir_.Append(app_mode::kAppShimSocketSymlinkName);
195   base::FilePath socket_path;
196   if (!base::ReadSymbolicLink(symlink_path, &socket_path)) {
197     // The path in the user data dir is not a symlink, try connecting directly.
198     CreateChannelAndSendLaunchApp(symlink_path);
199     return;
200   }
202   app_mode::VerifySocketPermissions(socket_path);
204   CreateChannelAndSendLaunchApp(socket_path);
207 void AppShimController::CreateChannelAndSendLaunchApp(
208     const base::FilePath& socket_path) {
209   IPC::ChannelHandle handle(socket_path.value());
210   channel_ = IPC::ChannelProxy::Create(handle,
211                                        IPC::Channel::MODE_NAMED_CLIENT,
212                                        this,
213                                        g_io_thread->message_loop_proxy().get());
215   bool launched_by_chrome = base::CommandLine::ForCurrentProcess()->HasSwitch(
216       app_mode::kLaunchedByChromeProcessId);
217   apps::AppShimLaunchType launch_type = launched_by_chrome ?
218           apps::APP_SHIM_LAUNCH_REGISTER_ONLY : apps::APP_SHIM_LAUNCH_NORMAL;
220   [delegate_ setController:this];
222   std::vector<base::FilePath> files;
223   [delegate_ getFilesToOpenAtStartup:&files];
225   channel_->Send(new AppShimHostMsg_LaunchApp(
226       g_info->profile_dir, g_info->app_mode_id, launch_type, files));
229 void AppShimController::SetUpMenu() {
230   NSString* title = base::SysUTF16ToNSString(g_info->app_mode_name);
232   // Create a main menu since [NSApp mainMenu] is nil.
233   base::scoped_nsobject<NSMenu> main_menu([[NSMenu alloc] initWithTitle:title]);
235   // The title of the first item is replaced by OSX with the name of the app and
236   // bold styling. Create a dummy item for this and make it hidden.
237   NSMenuItem* dummy_item = [main_menu addItemWithTitle:title
238                                                 action:nil
239                                          keyEquivalent:@""];
240   base::scoped_nsobject<NSMenu> dummy_submenu(
241       [[NSMenu alloc] initWithTitle:title]);
242   [dummy_item setSubmenu:dummy_submenu];
243   [dummy_item setHidden:YES];
245   // Construct an unbolded app menu, to match how it appears in the Chrome menu
246   // bar when the app is focused.
247   NSMenuItem* item = [main_menu addItemWithTitle:title
248                                           action:nil
249                                    keyEquivalent:@""];
250   base::scoped_nsobject<NSMenu> submenu([[NSMenu alloc] initWithTitle:title]);
251   [item setSubmenu:submenu];
253   // Add a quit entry.
254   NSString* quit_localized_string =
255       l10n_util::GetNSStringF(IDS_EXIT_MAC, g_info->app_mode_name);
256   [submenu addItemWithTitle:quit_localized_string
257                      action:@selector(terminate:)
258               keyEquivalent:@"q"];
260   // Add File, Edit, and Window menus. These are just here to make the
261   // transition smoother, i.e. from another application to the shim then to
262   // Chrome.
263   [main_menu addItemWithTitle:l10n_util::GetNSString(IDS_FILE_MENU_MAC)
264                        action:nil
265                 keyEquivalent:@""];
266   [main_menu addItemWithTitle:l10n_util::GetNSString(IDS_EDIT_MENU_MAC)
267                        action:nil
268                 keyEquivalent:@""];
269   [main_menu addItemWithTitle:l10n_util::GetNSString(IDS_WINDOW_MENU_MAC)
270                        action:nil
271                 keyEquivalent:@""];
273   [NSApp setMainMenu:main_menu];
276 void AppShimController::SendQuitApp() {
277   channel_->Send(new AppShimHostMsg_QuitApp);
280 bool AppShimController::OnMessageReceived(const IPC::Message& message) {
281   bool handled = true;
282   IPC_BEGIN_MESSAGE_MAP(AppShimController, message)
283     IPC_MESSAGE_HANDLER(AppShimMsg_LaunchApp_Done, OnLaunchAppDone)
284     IPC_MESSAGE_HANDLER(AppShimMsg_Hide, OnHide)
285     IPC_MESSAGE_HANDLER(AppShimMsg_RequestUserAttention, OnRequestUserAttention)
286     IPC_MESSAGE_HANDLER(AppShimMsg_SetUserAttention, OnSetUserAttention)
287     IPC_MESSAGE_UNHANDLED(handled = false)
288   IPC_END_MESSAGE_MAP()
290   return handled;
293 void AppShimController::OnChannelError() {
294   Close();
297 void AppShimController::OnLaunchAppDone(apps::AppShimLaunchResult result) {
298   if (result != apps::APP_SHIM_LAUNCH_SUCCESS) {
299     Close();
300     return;
301   }
303   std::vector<base::FilePath> files;
304   if ([delegate_ getFilesToOpenAtStartup:&files])
305     SendFocusApp(apps::APP_SHIM_FOCUS_OPEN_FILES, files);
307   launch_app_done_ = true;
310 void AppShimController::OnHide() {
311   [NSApp hide:nil];
314 void AppShimController::OnRequestUserAttention() {
315   OnSetUserAttention(apps::APP_SHIM_ATTENTION_INFORMATIONAL);
318 void AppShimController::OnSetUserAttention(
319     apps::AppShimAttentionType attention_type) {
320   switch (attention_type) {
321     case apps::APP_SHIM_ATTENTION_CANCEL:
322       [NSApp cancelUserAttentionRequest:attention_request_id_];
323       attention_request_id_ = 0;
324       break;
325     case apps::APP_SHIM_ATTENTION_CRITICAL:
326       attention_request_id_ = [NSApp requestUserAttention:NSCriticalRequest];
327       break;
328     case apps::APP_SHIM_ATTENTION_INFORMATIONAL:
329       attention_request_id_ =
330           [NSApp requestUserAttention:NSInformationalRequest];
331       break;
332     case apps::APP_SHIM_ATTENTION_NUM_TYPES:
333       NOTREACHED();
334   }
337 void AppShimController::Close() {
338   [delegate_ terminateNow];
341 bool AppShimController::SendFocusApp(apps::AppShimFocusType focus_type,
342                                      const std::vector<base::FilePath>& files) {
343   if (launch_app_done_) {
344     channel_->Send(new AppShimHostMsg_FocusApp(focus_type, files));
345     return true;
346   }
348   return false;
351 void AppShimController::SendSetAppHidden(bool hidden) {
352   channel_->Send(new AppShimHostMsg_SetAppHidden(hidden));
355 @implementation AppShimDelegate
357 - (BOOL)getFilesToOpenAtStartup:(std::vector<base::FilePath>*)out {
358   if (filesToOpenAtStartup_.empty())
359     return NO;
361   out->insert(out->end(),
362               filesToOpenAtStartup_.begin(),
363               filesToOpenAtStartup_.end());
364   filesToOpenAtStartup_.clear();
365   return YES;
368 - (void)setController:(AppShimController*)controller {
369   appShimController_ = controller;
372 - (void)openFiles:(NSArray*)filenames {
373   std::vector<base::FilePath> filePaths;
374   for (NSString* filename in filenames)
375     filePaths.push_back(base::mac::NSStringToFilePath(filename));
377   // If the AppShimController is ready, try to send a FocusApp. If that fails,
378   // (e.g. if launching has not finished), enqueue the files.
379   if (appShimController_ &&
380       appShimController_->SendFocusApp(apps::APP_SHIM_FOCUS_OPEN_FILES,
381                                        filePaths)) {
382     return;
383   }
385   filesToOpenAtStartup_.insert(filesToOpenAtStartup_.end(),
386                                filePaths.begin(),
387                                filePaths.end());
390 - (BOOL)application:(NSApplication*)app
391            openFile:(NSString*)filename {
392   [self openFiles:@[filename]];
393   return YES;
396 - (void)application:(NSApplication*)app
397           openFiles:(NSArray*)filenames {
398   [self openFiles:filenames];
399   [app replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
402 - (BOOL)applicationOpenUntitledFile:(NSApplication*)app {
403   if (appShimController_) {
404     return appShimController_->SendFocusApp(apps::APP_SHIM_FOCUS_REOPEN,
405                                             std::vector<base::FilePath>());
406   }
408   return NO;
411 - (void)applicationWillBecomeActive:(NSNotification*)notification {
412   if (appShimController_) {
413     appShimController_->SendFocusApp(apps::APP_SHIM_FOCUS_NORMAL,
414                                      std::vector<base::FilePath>());
415   }
418 - (NSApplicationTerminateReply)
419     applicationShouldTerminate:(NSApplication*)sender {
420   if (terminateNow_ || !appShimController_)
421     return NSTerminateNow;
423   appShimController_->SendQuitApp();
424   // Wait for the channel to close before terminating.
425   terminateRequested_ = YES;
426   return NSTerminateLater;
429 - (void)applicationWillHide:(NSNotification*)notification {
430   if (appShimController_)
431     appShimController_->SendSetAppHidden(true);
434 - (void)applicationWillUnhide:(NSNotification*)notification {
435   if (appShimController_)
436     appShimController_->SendSetAppHidden(false);
439 - (void)terminateNow {
440   if (terminateRequested_) {
441     [NSApp replyToApplicationShouldTerminate:NSTerminateNow];
442     return;
443   }
445   terminateNow_ = YES;
446   [NSApp terminate:nil];
449 @end
451 //-----------------------------------------------------------------------------
453 // A ReplyEventHandler is a helper class to send an Apple Event to a process
454 // and call a callback when the reply returns.
456 // This is used to 'ping' the main Chrome process -- once Chrome has sent back
457 // an Apple Event reply, it's guaranteed that it has opened the IPC channel
458 // that the app shim will connect to.
459 @interface ReplyEventHandler : NSObject {
460   base::Callback<void(bool)> onReply_;
461   AEDesc replyEvent_;
463 // Sends an Apple Event to the process identified by |psn|, and calls |replyFn|
464 // when the reply is received. Internally this creates a ReplyEventHandler,
465 // which will delete itself once the reply event has been received.
466 + (void)pingProcess:(const ProcessSerialNumber&)psn
467             andCall:(base::Callback<void(bool)>)replyFn;
468 @end
470 @interface ReplyEventHandler (PrivateMethods)
471 // Initialise the reply event handler. Doesn't register any handlers until
472 // |-pingProcess:| is called. |replyFn| is the function to be called when the
473 // Apple Event reply arrives.
474 - (id)initWithCallback:(base::Callback<void(bool)>)replyFn;
476 // Sends an Apple Event ping to the process identified by |psn| and registers
477 // to listen for a reply.
478 - (void)pingProcess:(const ProcessSerialNumber&)psn;
480 // Called when a response is received from the target process for the ping sent
481 // by |-pingProcess:|.
482 - (void)message:(NSAppleEventDescriptor*)event
483       withReply:(NSAppleEventDescriptor*)reply;
485 // Calls |onReply_|, passing it |success| to specify whether the ping was
486 // successful.
487 - (void)closeWithSuccess:(bool)success;
488 @end
490 @implementation ReplyEventHandler
491 + (void)pingProcess:(const ProcessSerialNumber&)psn
492             andCall:(base::Callback<void(bool)>)replyFn {
493   // The object will release itself when the reply arrives, or possibly earlier
494   // if an unrecoverable error occurs.
495   ReplyEventHandler* handler =
496       [[ReplyEventHandler alloc] initWithCallback:replyFn];
497   [handler pingProcess:psn];
499 @end
501 @implementation ReplyEventHandler (PrivateMethods)
502 - (id)initWithCallback:(base::Callback<void(bool)>)replyFn {
503   if ((self = [super init])) {
504     onReply_ = replyFn;
505   }
506   return self;
509 - (void)pingProcess:(const ProcessSerialNumber&)psn {
510   // Register the reply listener.
511   NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
512   [em setEventHandler:self
513           andSelector:@selector(message:withReply:)
514         forEventClass:'aevt'
515            andEventID:'ansr'];
516   // Craft the Apple Event to send.
517   NSAppleEventDescriptor* target = [NSAppleEventDescriptor
518       descriptorWithDescriptorType:typeProcessSerialNumber
519                              bytes:&psn
520                             length:sizeof(psn)];
521   NSAppleEventDescriptor* initial_event =
522       [NSAppleEventDescriptor
523           appleEventWithEventClass:app_mode::kAEChromeAppClass
524                            eventID:app_mode::kAEChromeAppPing
525                   targetDescriptor:target
526                           returnID:kAutoGenerateReturnID
527                      transactionID:kAnyTransactionID];
529   // Note that AESendMessage effectively ignores kAEDefaultTimeout, because this
530   // call does not pass kAEWantReceipt (which is deprecated and unsupported on
531   // Mac). Instead, rely on OnPingChromeTimeout().
532   OSStatus status = AESendMessage(
533       [initial_event aeDesc], &replyEvent_, kAEQueueReply, kAEDefaultTimeout);
534   if (status != noErr) {
535     OSSTATUS_LOG(ERROR, status) << "AESendMessage";
536     [self closeWithSuccess:false];
537   }
540 - (void)message:(NSAppleEventDescriptor*)event
541       withReply:(NSAppleEventDescriptor*)reply {
542   [self closeWithSuccess:true];
545 - (void)closeWithSuccess:(bool)success {
546   onReply_.Run(success);
547   NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
548   [em removeEventHandlerForEventClass:'aevt' andEventID:'ansr'];
549   [self release];
551 @end
553 //-----------------------------------------------------------------------------
555 extern "C" {
557 // |ChromeAppModeStart()| is the point of entry into the framework from the app
558 // mode loader.
559 __attribute__((visibility("default")))
560 int ChromeAppModeStart(const app_mode::ChromeAppModeInfo* info);
562 }  // extern "C"
564 int ChromeAppModeStart(const app_mode::ChromeAppModeInfo* info) {
565   base::CommandLine::Init(info->argc, info->argv);
567   base::mac::ScopedNSAutoreleasePool scoped_pool;
568   base::AtExitManager exit_manager;
569   chrome::RegisterPathProvider();
571   if (info->major_version < app_mode::kCurrentChromeAppModeInfoMajorVersion) {
572     RAW_LOG(ERROR, "App Mode Loader too old.");
573     return 1;
574   }
575   if (info->major_version > app_mode::kCurrentChromeAppModeInfoMajorVersion) {
576     RAW_LOG(ERROR, "Browser Framework too old to load App Shortcut.");
577     return 1;
578   }
580   g_info = info;
582   // Set bundle paths. This loads the bundles.
583   base::mac::SetOverrideOuterBundlePath(g_info->chrome_outer_bundle_path);
584   base::mac::SetOverrideFrameworkBundlePath(
585       g_info->chrome_versioned_path.Append(chrome::kFrameworkName));
587   // Calculate the preferred locale used by Chrome.
588   // We can't use l10n_util::OverrideLocaleWithCocoaLocale() because it calls
589   // [base::mac::OuterBundle() preferredLocalizations] which gets localizations
590   // from the bundle of the running app (i.e. it is equivalent to
591   // [[NSBundle mainBundle] preferredLocalizations]) instead of the target
592   // bundle.
593   NSArray* preferred_languages = [NSLocale preferredLanguages];
594   NSArray* supported_languages = [base::mac::OuterBundle() localizations];
595   std::string preferred_localization;
596   for (NSString* language in preferred_languages) {
597     if ([supported_languages containsObject:language]) {
598       preferred_localization = base::SysNSStringToUTF8(language);
599       break;
600     }
601   }
602   std::string locale = l10n_util::NormalizeLocale(
603       l10n_util::GetApplicationLocale(preferred_localization));
605   // Load localized strings.
606   ui::ResourceBundle::InitSharedInstanceWithLocale(
607       locale, NULL, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
609   // Launch the IO thread.
610   base::Thread::Options io_thread_options;
611   io_thread_options.message_loop_type = base::MessageLoop::TYPE_IO;
612   base::Thread *io_thread = new base::Thread("CrAppShimIO");
613   io_thread->StartWithOptions(io_thread_options);
614   g_io_thread = io_thread;
616   // Find already running instances of Chrome.
617   pid_t pid = -1;
618   std::string chrome_process_id =
619       base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
620           app_mode::kLaunchedByChromeProcessId);
621   if (!chrome_process_id.empty()) {
622     if (!base::StringToInt(chrome_process_id, &pid))
623       LOG(FATAL) << "Invalid PID: " << chrome_process_id;
624   } else {
625     NSString* chrome_bundle_id = [base::mac::OuterBundle() bundleIdentifier];
626     NSArray* existing_chrome = [NSRunningApplication
627         runningApplicationsWithBundleIdentifier:chrome_bundle_id];
628     if ([existing_chrome count] > 0)
629       pid = [[existing_chrome objectAtIndex:0] processIdentifier];
630   }
632   AppShimController controller;
633   base::MessageLoopForUI main_message_loop;
634   main_message_loop.set_thread_name("MainThread");
635   base::PlatformThread::SetName("CrAppShimMain");
637   // In tests, launching Chrome does nothing, and we won't get a ping response,
638   // so just assume the socket exists.
639   if (pid == -1 &&
640       !base::CommandLine::ForCurrentProcess()->HasSwitch(
641           app_mode::kLaunchedForTest)) {
642     // Launch Chrome if it isn't already running.
643     ProcessSerialNumber psn;
644     base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
645     command_line.AppendSwitch(switches::kSilentLaunch);
647     // If the shim is the app launcher, pass --show-app-list when starting a new
648     // Chrome process to inform startup codepaths and load the correct profile.
649     if (info->app_mode_id == app_mode::kAppListModeId) {
650       command_line.AppendSwitch(switches::kShowAppList);
651     } else {
652       command_line.AppendSwitchPath(switches::kProfileDirectory,
653                                     info->profile_dir);
654     }
656     bool success =
657         base::mac::OpenApplicationWithPath(base::mac::OuterBundlePath(),
658                                            command_line,
659                                            kLSLaunchDefaults,
660                                            &psn);
661     if (!success)
662       return 1;
664     base::Callback<void(bool)> on_ping_chrome_reply =
665         base::Bind(&AppShimController::OnPingChromeReply,
666                    base::Unretained(&controller));
668     // This code abuses the fact that Apple Events sent before the process is
669     // fully initialized don't receive a reply until its run loop starts. Once
670     // the reply is received, Chrome will have opened its IPC port, guaranteed.
671     [ReplyEventHandler pingProcess:psn
672                            andCall:on_ping_chrome_reply];
674     main_message_loop.PostDelayedTask(
675         FROM_HERE,
676         base::Bind(&AppShimController::OnPingChromeTimeout,
677                    base::Unretained(&controller)),
678         base::TimeDelta::FromSeconds(kPingChromeTimeoutSeconds));
679   } else {
680     // Chrome already running. Proceed to init. This could still fail if Chrome
681     // is still starting up or shutting down, but the process will exit quickly,
682     // which is preferable to waiting for the Apple Event to timeout after one
683     // minute.
684     main_message_loop.PostTask(
685         FROM_HERE,
686         base::Bind(&AppShimController::Init,
687                    base::Unretained(&controller)));
688   }
690   main_message_loop.Run();
691   return 0;