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
10 #import <Cocoa/Cocoa.h>
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"
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;
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> {
60 AppShimController* appShimController_; // Weak, initially NULL.
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
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 {
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.
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.
109 void SendSetAppHidden(bool hidden);
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);
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);
131 // Requests user attention.
132 void OnRequestUserAttention();
133 void OnSetUserAttention(apps::AppShimAttentionType attention_type);
135 // Terminates the app shim process.
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;
166 [NSApp terminate:nil];
173 void AppShimController::OnPingChromeTimeout() {
174 if (!ping_chrome_reply_received_)
175 [NSApp terminate:nil];
178 void AppShimController::Init() {
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);
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,
213 g_io_thread->message_loop_proxy().get());
215 bool launched_by_chrome =
216 CommandLine::ForCurrentProcess()->HasSwitch(
217 app_mode::kLaunchedByChromeProcessId);
218 apps::AppShimLaunchType launch_type = launched_by_chrome ?
219 apps::APP_SHIM_LAUNCH_REGISTER_ONLY : apps::APP_SHIM_LAUNCH_NORMAL;
221 [delegate_ setController:this];
223 std::vector<base::FilePath> files;
224 [delegate_ getFilesToOpenAtStartup:&files];
226 channel_->Send(new AppShimHostMsg_LaunchApp(
227 g_info->profile_dir, g_info->app_mode_id, launch_type, files));
230 void AppShimController::SetUpMenu() {
231 NSString* title = base::SysUTF16ToNSString(g_info->app_mode_name);
233 // Create a main menu since [NSApp mainMenu] is nil.
234 base::scoped_nsobject<NSMenu> main_menu([[NSMenu alloc] initWithTitle:title]);
236 // The title of the first item is replaced by OSX with the name of the app and
237 // bold styling. Create a dummy item for this and make it hidden.
238 NSMenuItem* dummy_item = [main_menu addItemWithTitle:title
241 base::scoped_nsobject<NSMenu> dummy_submenu(
242 [[NSMenu alloc] initWithTitle:title]);
243 [dummy_item setSubmenu:dummy_submenu];
244 [dummy_item setHidden:YES];
246 // Construct an unbolded app menu, to match how it appears in the Chrome menu
247 // bar when the app is focused.
248 NSMenuItem* item = [main_menu addItemWithTitle:title
251 base::scoped_nsobject<NSMenu> submenu([[NSMenu alloc] initWithTitle:title]);
252 [item setSubmenu:submenu];
255 NSString* quit_localized_string =
256 l10n_util::GetNSStringF(IDS_EXIT_MAC, g_info->app_mode_name);
257 [submenu addItemWithTitle:quit_localized_string
258 action:@selector(terminate:)
261 // Add File, Edit, and Window menus. These are just here to make the
262 // transition smoother, i.e. from another application to the shim then to
264 [main_menu addItemWithTitle:l10n_util::GetNSString(IDS_FILE_MENU_MAC)
267 [main_menu addItemWithTitle:l10n_util::GetNSString(IDS_EDIT_MENU_MAC)
270 [main_menu addItemWithTitle:l10n_util::GetNSString(IDS_WINDOW_MENU_MAC)
274 [NSApp setMainMenu:main_menu];
277 void AppShimController::SendQuitApp() {
278 channel_->Send(new AppShimHostMsg_QuitApp);
281 bool AppShimController::OnMessageReceived(const IPC::Message& message) {
283 IPC_BEGIN_MESSAGE_MAP(AppShimController, message)
284 IPC_MESSAGE_HANDLER(AppShimMsg_LaunchApp_Done, OnLaunchAppDone)
285 IPC_MESSAGE_HANDLER(AppShimMsg_Hide, OnHide)
286 IPC_MESSAGE_HANDLER(AppShimMsg_RequestUserAttention, OnRequestUserAttention)
287 IPC_MESSAGE_HANDLER(AppShimMsg_SetUserAttention, OnSetUserAttention)
288 IPC_MESSAGE_UNHANDLED(handled = false)
289 IPC_END_MESSAGE_MAP()
294 void AppShimController::OnChannelError() {
298 void AppShimController::OnLaunchAppDone(apps::AppShimLaunchResult result) {
299 if (result != apps::APP_SHIM_LAUNCH_SUCCESS) {
304 std::vector<base::FilePath> files;
305 if ([delegate_ getFilesToOpenAtStartup:&files])
306 SendFocusApp(apps::APP_SHIM_FOCUS_OPEN_FILES, files);
308 launch_app_done_ = true;
311 void AppShimController::OnHide() {
315 void AppShimController::OnRequestUserAttention() {
316 OnSetUserAttention(apps::APP_SHIM_ATTENTION_INFORMATIONAL);
319 void AppShimController::OnSetUserAttention(
320 apps::AppShimAttentionType attention_type) {
321 switch (attention_type) {
322 case apps::APP_SHIM_ATTENTION_CANCEL:
323 [NSApp cancelUserAttentionRequest:attention_request_id_];
324 attention_request_id_ = 0;
326 case apps::APP_SHIM_ATTENTION_CRITICAL:
327 attention_request_id_ = [NSApp requestUserAttention:NSCriticalRequest];
329 case apps::APP_SHIM_ATTENTION_INFORMATIONAL:
330 attention_request_id_ =
331 [NSApp requestUserAttention:NSInformationalRequest];
333 case apps::APP_SHIM_ATTENTION_NUM_TYPES:
338 void AppShimController::Close() {
339 [delegate_ terminateNow];
342 bool AppShimController::SendFocusApp(apps::AppShimFocusType focus_type,
343 const std::vector<base::FilePath>& files) {
344 if (launch_app_done_) {
345 channel_->Send(new AppShimHostMsg_FocusApp(focus_type, files));
352 void AppShimController::SendSetAppHidden(bool hidden) {
353 channel_->Send(new AppShimHostMsg_SetAppHidden(hidden));
356 @implementation AppShimDelegate
358 - (BOOL)getFilesToOpenAtStartup:(std::vector<base::FilePath>*)out {
359 if (filesToOpenAtStartup_.empty())
362 out->insert(out->end(),
363 filesToOpenAtStartup_.begin(),
364 filesToOpenAtStartup_.end());
365 filesToOpenAtStartup_.clear();
369 - (void)setController:(AppShimController*)controller {
370 appShimController_ = controller;
373 - (void)openFiles:(NSArray*)filenames {
374 std::vector<base::FilePath> filePaths;
375 for (NSString* filename in filenames)
376 filePaths.push_back(base::mac::NSStringToFilePath(filename));
378 // If the AppShimController is ready, try to send a FocusApp. If that fails,
379 // (e.g. if launching has not finished), enqueue the files.
380 if (appShimController_ &&
381 appShimController_->SendFocusApp(apps::APP_SHIM_FOCUS_OPEN_FILES,
386 filesToOpenAtStartup_.insert(filesToOpenAtStartup_.end(),
391 - (BOOL)application:(NSApplication*)app
392 openFile:(NSString*)filename {
393 [self openFiles:@[filename]];
397 - (void)application:(NSApplication*)app
398 openFiles:(NSArray*)filenames {
399 [self openFiles:filenames];
400 [app replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
403 - (BOOL)applicationOpenUntitledFile:(NSApplication*)app {
404 if (appShimController_) {
405 return appShimController_->SendFocusApp(apps::APP_SHIM_FOCUS_REOPEN,
406 std::vector<base::FilePath>());
412 - (void)applicationWillBecomeActive:(NSNotification*)notification {
413 if (appShimController_) {
414 appShimController_->SendFocusApp(apps::APP_SHIM_FOCUS_NORMAL,
415 std::vector<base::FilePath>());
419 - (NSApplicationTerminateReply)
420 applicationShouldTerminate:(NSApplication*)sender {
421 if (terminateNow_ || !appShimController_)
422 return NSTerminateNow;
424 appShimController_->SendQuitApp();
425 // Wait for the channel to close before terminating.
426 terminateRequested_ = YES;
427 return NSTerminateLater;
430 - (void)applicationWillHide:(NSNotification*)notification {
431 if (appShimController_)
432 appShimController_->SendSetAppHidden(true);
435 - (void)applicationWillUnhide:(NSNotification*)notification {
436 if (appShimController_)
437 appShimController_->SendSetAppHidden(false);
440 - (void)terminateNow {
441 if (terminateRequested_) {
442 [NSApp replyToApplicationShouldTerminate:NSTerminateNow];
447 [NSApp terminate:nil];
452 //-----------------------------------------------------------------------------
454 // A ReplyEventHandler is a helper class to send an Apple Event to a process
455 // and call a callback when the reply returns.
457 // This is used to 'ping' the main Chrome process -- once Chrome has sent back
458 // an Apple Event reply, it's guaranteed that it has opened the IPC channel
459 // that the app shim will connect to.
460 @interface ReplyEventHandler : NSObject {
461 base::Callback<void(bool)> onReply_;
464 // Sends an Apple Event to the process identified by |psn|, and calls |replyFn|
465 // when the reply is received. Internally this creates a ReplyEventHandler,
466 // which will delete itself once the reply event has been received.
467 + (void)pingProcess:(const ProcessSerialNumber&)psn
468 andCall:(base::Callback<void(bool)>)replyFn;
471 @interface ReplyEventHandler (PrivateMethods)
472 // Initialise the reply event handler. Doesn't register any handlers until
473 // |-pingProcess:| is called. |replyFn| is the function to be called when the
474 // Apple Event reply arrives.
475 - (id)initWithCallback:(base::Callback<void(bool)>)replyFn;
477 // Sends an Apple Event ping to the process identified by |psn| and registers
478 // to listen for a reply.
479 - (void)pingProcess:(const ProcessSerialNumber&)psn;
481 // Called when a response is received from the target process for the ping sent
482 // by |-pingProcess:|.
483 - (void)message:(NSAppleEventDescriptor*)event
484 withReply:(NSAppleEventDescriptor*)reply;
486 // Calls |onReply_|, passing it |success| to specify whether the ping was
488 - (void)closeWithSuccess:(bool)success;
491 @implementation ReplyEventHandler
492 + (void)pingProcess:(const ProcessSerialNumber&)psn
493 andCall:(base::Callback<void(bool)>)replyFn {
494 // The object will release itself when the reply arrives, or possibly earlier
495 // if an unrecoverable error occurs.
496 ReplyEventHandler* handler =
497 [[ReplyEventHandler alloc] initWithCallback:replyFn];
498 [handler pingProcess:psn];
502 @implementation ReplyEventHandler (PrivateMethods)
503 - (id)initWithCallback:(base::Callback<void(bool)>)replyFn {
504 if ((self = [super init])) {
510 - (void)pingProcess:(const ProcessSerialNumber&)psn {
511 // Register the reply listener.
512 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
513 [em setEventHandler:self
514 andSelector:@selector(message:withReply:)
517 // Craft the Apple Event to send.
518 NSAppleEventDescriptor* target = [NSAppleEventDescriptor
519 descriptorWithDescriptorType:typeProcessSerialNumber
522 NSAppleEventDescriptor* initial_event =
523 [NSAppleEventDescriptor
524 appleEventWithEventClass:app_mode::kAEChromeAppClass
525 eventID:app_mode::kAEChromeAppPing
526 targetDescriptor:target
527 returnID:kAutoGenerateReturnID
528 transactionID:kAnyTransactionID];
530 // Note that AESendMessage effectively ignores kAEDefaultTimeout, because this
531 // call does not pass kAEWantReceipt (which is deprecated and unsupported on
532 // Mac). Instead, rely on OnPingChromeTimeout().
533 OSStatus status = AESendMessage(
534 [initial_event aeDesc], &replyEvent_, kAEQueueReply, kAEDefaultTimeout);
535 if (status != noErr) {
536 OSSTATUS_LOG(ERROR, status) << "AESendMessage";
537 [self closeWithSuccess:false];
541 - (void)message:(NSAppleEventDescriptor*)event
542 withReply:(NSAppleEventDescriptor*)reply {
543 [self closeWithSuccess:true];
546 - (void)closeWithSuccess:(bool)success {
547 onReply_.Run(success);
548 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
549 [em removeEventHandlerForEventClass:'aevt' andEventID:'ansr'];
554 //-----------------------------------------------------------------------------
558 // |ChromeAppModeStart()| is the point of entry into the framework from the app
560 __attribute__((visibility("default")))
561 int ChromeAppModeStart(const app_mode::ChromeAppModeInfo* info);
565 int ChromeAppModeStart(const app_mode::ChromeAppModeInfo* info) {
566 CommandLine::Init(info->argc, info->argv);
568 base::mac::ScopedNSAutoreleasePool scoped_pool;
569 base::AtExitManager exit_manager;
570 chrome::RegisterPathProvider();
572 if (info->major_version < app_mode::kCurrentChromeAppModeInfoMajorVersion) {
573 RAW_LOG(ERROR, "App Mode Loader too old.");
576 if (info->major_version > app_mode::kCurrentChromeAppModeInfoMajorVersion) {
577 RAW_LOG(ERROR, "Browser Framework too old to load App Shortcut.");
583 // Set bundle paths. This loads the bundles.
584 base::mac::SetOverrideOuterBundlePath(g_info->chrome_outer_bundle_path);
585 base::mac::SetOverrideFrameworkBundlePath(
586 g_info->chrome_versioned_path.Append(chrome::kFrameworkName));
588 // Calculate the preferred locale used by Chrome.
589 // We can't use l10n_util::OverrideLocaleWithCocoaLocale() because it calls
590 // [base::mac::OuterBundle() preferredLocalizations] which gets localizations
591 // from the bundle of the running app (i.e. it is equivalent to
592 // [[NSBundle mainBundle] preferredLocalizations]) instead of the target
594 NSArray* preferred_languages = [NSLocale preferredLanguages];
595 NSArray* supported_languages = [base::mac::OuterBundle() localizations];
596 std::string preferred_localization;
597 for (NSString* language in preferred_languages) {
598 if ([supported_languages containsObject:language]) {
599 preferred_localization = base::SysNSStringToUTF8(language);
603 std::string locale = l10n_util::NormalizeLocale(
604 l10n_util::GetApplicationLocale(preferred_localization));
606 // Load localized strings.
607 ui::ResourceBundle::InitSharedInstanceWithLocale(
608 locale, NULL, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
610 // Launch the IO thread.
611 base::Thread::Options io_thread_options;
612 io_thread_options.message_loop_type = base::MessageLoop::TYPE_IO;
613 base::Thread *io_thread = new base::Thread("CrAppShimIO");
614 io_thread->StartWithOptions(io_thread_options);
615 g_io_thread = io_thread;
617 // Find already running instances of Chrome.
619 std::string chrome_process_id = CommandLine::ForCurrentProcess()->
620 GetSwitchValueASCII(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;
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];
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.
640 !CommandLine::ForCurrentProcess()->HasSwitch(
641 app_mode::kLaunchedForTest)) {
642 // Launch Chrome if it isn't already running.
643 ProcessSerialNumber psn;
644 CommandLine command_line(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);
652 command_line.AppendSwitchPath(switches::kProfileDirectory,
657 base::mac::OpenApplicationWithPath(base::mac::OuterBundlePath(),
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(
676 base::Bind(&AppShimController::OnPingChromeTimeout,
677 base::Unretained(&controller)),
678 base::TimeDelta::FromSeconds(kPingChromeTimeoutSeconds));
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
684 main_message_loop.PostTask(
686 base::Bind(&AppShimController::Init,
687 base::Unretained(&controller)));
690 main_message_loop.Run();