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 // Set this app to the unhidden state. Happens when an app window shows
133 void OnUnhideWithoutActivation();
135 // Requests user attention.
136 void OnRequestUserAttention();
137 void OnSetUserAttention(apps::AppShimAttentionType attention_type);
139 // Terminates the app shim process.
142 base::FilePath user_data_dir_;
143 scoped_ptr<IPC::ChannelProxy> channel_;
144 base::scoped_nsobject<AppShimDelegate> delegate_;
145 bool launch_app_done_;
146 bool ping_chrome_reply_received_;
147 NSInteger attention_request_id_;
149 DISALLOW_COPY_AND_ASSIGN(AppShimController);
152 AppShimController::AppShimController()
153 : delegate_([[AppShimDelegate alloc] init]),
154 launch_app_done_(false),
155 ping_chrome_reply_received_(false),
156 attention_request_id_(0) {
157 // Since AppShimController is created before the main message loop starts,
158 // NSApp will not be set, so use sharedApplication.
159 [[NSApplication sharedApplication] setDelegate:delegate_];
162 AppShimController::~AppShimController() {
163 // Un-set the delegate since NSApplication does not retain it.
164 [[NSApplication sharedApplication] setDelegate:nil];
167 void AppShimController::OnPingChromeReply(bool success) {
168 ping_chrome_reply_received_ = true;
170 [NSApp terminate:nil];
177 void AppShimController::OnPingChromeTimeout() {
178 if (!ping_chrome_reply_received_)
179 [NSApp terminate:nil];
182 void AppShimController::Init() {
187 // Chrome will relaunch shims when relaunching apps.
188 if (base::mac::IsOSLionOrLater())
189 [NSApp disableRelaunchOnLogin];
191 // The user_data_dir for shims actually contains the app_data_path.
192 // I.e. <user_data_dir>/<profile_dir>/Web Applications/_crx_extensionid/
193 user_data_dir_ = g_info->user_data_dir.DirName().DirName().DirName();
194 CHECK(!user_data_dir_.empty());
196 base::FilePath symlink_path =
197 user_data_dir_.Append(app_mode::kAppShimSocketSymlinkName);
199 base::FilePath socket_path;
200 if (!base::ReadSymbolicLink(symlink_path, &socket_path)) {
201 // The path in the user data dir is not a symlink, try connecting directly.
202 CreateChannelAndSendLaunchApp(symlink_path);
206 app_mode::VerifySocketPermissions(socket_path);
208 CreateChannelAndSendLaunchApp(socket_path);
211 void AppShimController::CreateChannelAndSendLaunchApp(
212 const base::FilePath& socket_path) {
213 IPC::ChannelHandle handle(socket_path.value());
214 channel_ = IPC::ChannelProxy::Create(handle, IPC::Channel::MODE_NAMED_CLIENT,
215 this, g_io_thread->task_runner().get());
217 bool launched_by_chrome = base::CommandLine::ForCurrentProcess()->HasSwitch(
218 app_mode::kLaunchedByChromeProcessId);
219 apps::AppShimLaunchType launch_type = launched_by_chrome ?
220 apps::APP_SHIM_LAUNCH_REGISTER_ONLY : apps::APP_SHIM_LAUNCH_NORMAL;
222 [delegate_ setController:this];
224 std::vector<base::FilePath> files;
225 [delegate_ getFilesToOpenAtStartup:&files];
227 channel_->Send(new AppShimHostMsg_LaunchApp(
228 g_info->profile_dir, g_info->app_mode_id, launch_type, files));
231 void AppShimController::SetUpMenu() {
232 NSString* title = base::SysUTF16ToNSString(g_info->app_mode_name);
234 // Create a main menu since [NSApp mainMenu] is nil.
235 base::scoped_nsobject<NSMenu> main_menu([[NSMenu alloc] initWithTitle:title]);
237 // The title of the first item is replaced by OSX with the name of the app and
238 // bold styling. Create a dummy item for this and make it hidden.
239 NSMenuItem* dummy_item = [main_menu addItemWithTitle:title
242 base::scoped_nsobject<NSMenu> dummy_submenu(
243 [[NSMenu alloc] initWithTitle:title]);
244 [dummy_item setSubmenu:dummy_submenu];
245 [dummy_item setHidden:YES];
247 // Construct an unbolded app menu, to match how it appears in the Chrome menu
248 // bar when the app is focused.
249 NSMenuItem* item = [main_menu addItemWithTitle:title
252 base::scoped_nsobject<NSMenu> submenu([[NSMenu alloc] initWithTitle:title]);
253 [item setSubmenu:submenu];
256 NSString* quit_localized_string =
257 l10n_util::GetNSStringF(IDS_EXIT_MAC, g_info->app_mode_name);
258 [submenu addItemWithTitle:quit_localized_string
259 action:@selector(terminate:)
262 // Add File, Edit, and Window menus. These are just here to make the
263 // transition smoother, i.e. from another application to the shim then to
265 [main_menu addItemWithTitle:l10n_util::GetNSString(IDS_FILE_MENU_MAC)
268 [main_menu addItemWithTitle:l10n_util::GetNSString(IDS_EDIT_MENU_MAC)
271 [main_menu addItemWithTitle:l10n_util::GetNSString(IDS_WINDOW_MENU_MAC)
275 [NSApp setMainMenu:main_menu];
278 void AppShimController::SendQuitApp() {
279 channel_->Send(new AppShimHostMsg_QuitApp);
282 bool AppShimController::OnMessageReceived(const IPC::Message& message) {
284 IPC_BEGIN_MESSAGE_MAP(AppShimController, message)
285 IPC_MESSAGE_HANDLER(AppShimMsg_LaunchApp_Done, OnLaunchAppDone)
286 IPC_MESSAGE_HANDLER(AppShimMsg_Hide, OnHide)
287 IPC_MESSAGE_HANDLER(AppShimMsg_UnhideWithoutActivation,
288 OnUnhideWithoutActivation)
289 IPC_MESSAGE_HANDLER(AppShimMsg_RequestUserAttention, OnRequestUserAttention)
290 IPC_MESSAGE_HANDLER(AppShimMsg_SetUserAttention, OnSetUserAttention)
291 IPC_MESSAGE_UNHANDLED(handled = false)
292 IPC_END_MESSAGE_MAP()
297 void AppShimController::OnChannelError() {
301 void AppShimController::OnLaunchAppDone(apps::AppShimLaunchResult result) {
302 if (result != apps::APP_SHIM_LAUNCH_SUCCESS) {
307 std::vector<base::FilePath> files;
308 if ([delegate_ getFilesToOpenAtStartup:&files])
309 SendFocusApp(apps::APP_SHIM_FOCUS_OPEN_FILES, files);
311 launch_app_done_ = true;
314 void AppShimController::OnHide() {
318 void AppShimController::OnUnhideWithoutActivation() {
319 [NSApp unhideWithoutActivation];
322 void AppShimController::OnRequestUserAttention() {
323 OnSetUserAttention(apps::APP_SHIM_ATTENTION_INFORMATIONAL);
326 void AppShimController::OnSetUserAttention(
327 apps::AppShimAttentionType attention_type) {
328 switch (attention_type) {
329 case apps::APP_SHIM_ATTENTION_CANCEL:
330 [NSApp cancelUserAttentionRequest:attention_request_id_];
331 attention_request_id_ = 0;
333 case apps::APP_SHIM_ATTENTION_CRITICAL:
334 attention_request_id_ = [NSApp requestUserAttention:NSCriticalRequest];
336 case apps::APP_SHIM_ATTENTION_INFORMATIONAL:
337 attention_request_id_ =
338 [NSApp requestUserAttention:NSInformationalRequest];
340 case apps::APP_SHIM_ATTENTION_NUM_TYPES:
345 void AppShimController::Close() {
346 [delegate_ terminateNow];
349 bool AppShimController::SendFocusApp(apps::AppShimFocusType focus_type,
350 const std::vector<base::FilePath>& files) {
351 if (launch_app_done_) {
352 channel_->Send(new AppShimHostMsg_FocusApp(focus_type, files));
359 void AppShimController::SendSetAppHidden(bool hidden) {
360 channel_->Send(new AppShimHostMsg_SetAppHidden(hidden));
363 @implementation AppShimDelegate
365 - (BOOL)getFilesToOpenAtStartup:(std::vector<base::FilePath>*)out {
366 if (filesToOpenAtStartup_.empty())
369 out->insert(out->end(),
370 filesToOpenAtStartup_.begin(),
371 filesToOpenAtStartup_.end());
372 filesToOpenAtStartup_.clear();
376 - (void)setController:(AppShimController*)controller {
377 appShimController_ = controller;
380 - (void)openFiles:(NSArray*)filenames {
381 std::vector<base::FilePath> filePaths;
382 for (NSString* filename in filenames)
383 filePaths.push_back(base::mac::NSStringToFilePath(filename));
385 // If the AppShimController is ready, try to send a FocusApp. If that fails,
386 // (e.g. if launching has not finished), enqueue the files.
387 if (appShimController_ &&
388 appShimController_->SendFocusApp(apps::APP_SHIM_FOCUS_OPEN_FILES,
393 filesToOpenAtStartup_.insert(filesToOpenAtStartup_.end(),
398 - (BOOL)application:(NSApplication*)app
399 openFile:(NSString*)filename {
400 [self openFiles:@[filename]];
404 - (void)application:(NSApplication*)app
405 openFiles:(NSArray*)filenames {
406 [self openFiles:filenames];
407 [app replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
410 - (BOOL)applicationOpenUntitledFile:(NSApplication*)app {
411 if (appShimController_) {
412 return appShimController_->SendFocusApp(apps::APP_SHIM_FOCUS_REOPEN,
413 std::vector<base::FilePath>());
419 - (void)applicationWillBecomeActive:(NSNotification*)notification {
420 if (appShimController_) {
421 appShimController_->SendFocusApp(apps::APP_SHIM_FOCUS_NORMAL,
422 std::vector<base::FilePath>());
426 - (NSApplicationTerminateReply)
427 applicationShouldTerminate:(NSApplication*)sender {
428 if (terminateNow_ || !appShimController_)
429 return NSTerminateNow;
431 appShimController_->SendQuitApp();
432 // Wait for the channel to close before terminating.
433 terminateRequested_ = YES;
434 return NSTerminateLater;
437 - (void)applicationWillHide:(NSNotification*)notification {
438 if (appShimController_)
439 appShimController_->SendSetAppHidden(true);
442 - (void)applicationWillUnhide:(NSNotification*)notification {
443 if (appShimController_)
444 appShimController_->SendSetAppHidden(false);
447 - (void)terminateNow {
448 if (terminateRequested_) {
449 [NSApp replyToApplicationShouldTerminate:NSTerminateNow];
454 [NSApp terminate:nil];
459 //-----------------------------------------------------------------------------
461 // A ReplyEventHandler is a helper class to send an Apple Event to a process
462 // and call a callback when the reply returns.
464 // This is used to 'ping' the main Chrome process -- once Chrome has sent back
465 // an Apple Event reply, it's guaranteed that it has opened the IPC channel
466 // that the app shim will connect to.
467 @interface ReplyEventHandler : NSObject {
468 base::Callback<void(bool)> onReply_;
471 // Sends an Apple Event to the process identified by |psn|, and calls |replyFn|
472 // when the reply is received. Internally this creates a ReplyEventHandler,
473 // which will delete itself once the reply event has been received.
474 + (void)pingProcess:(const ProcessSerialNumber&)psn
475 andCall:(base::Callback<void(bool)>)replyFn;
478 @interface ReplyEventHandler (PrivateMethods)
479 // Initialise the reply event handler. Doesn't register any handlers until
480 // |-pingProcess:| is called. |replyFn| is the function to be called when the
481 // Apple Event reply arrives.
482 - (id)initWithCallback:(base::Callback<void(bool)>)replyFn;
484 // Sends an Apple Event ping to the process identified by |psn| and registers
485 // to listen for a reply.
486 - (void)pingProcess:(const ProcessSerialNumber&)psn;
488 // Called when a response is received from the target process for the ping sent
489 // by |-pingProcess:|.
490 - (void)message:(NSAppleEventDescriptor*)event
491 withReply:(NSAppleEventDescriptor*)reply;
493 // Calls |onReply_|, passing it |success| to specify whether the ping was
495 - (void)closeWithSuccess:(bool)success;
498 @implementation ReplyEventHandler
499 + (void)pingProcess:(const ProcessSerialNumber&)psn
500 andCall:(base::Callback<void(bool)>)replyFn {
501 // The object will release itself when the reply arrives, or possibly earlier
502 // if an unrecoverable error occurs.
503 ReplyEventHandler* handler =
504 [[ReplyEventHandler alloc] initWithCallback:replyFn];
505 [handler pingProcess:psn];
509 @implementation ReplyEventHandler (PrivateMethods)
510 - (id)initWithCallback:(base::Callback<void(bool)>)replyFn {
511 if ((self = [super init])) {
517 - (void)pingProcess:(const ProcessSerialNumber&)psn {
518 // Register the reply listener.
519 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
520 [em setEventHandler:self
521 andSelector:@selector(message:withReply:)
524 // Craft the Apple Event to send.
525 NSAppleEventDescriptor* target = [NSAppleEventDescriptor
526 descriptorWithDescriptorType:typeProcessSerialNumber
529 NSAppleEventDescriptor* initial_event =
530 [NSAppleEventDescriptor
531 appleEventWithEventClass:app_mode::kAEChromeAppClass
532 eventID:app_mode::kAEChromeAppPing
533 targetDescriptor:target
534 returnID:kAutoGenerateReturnID
535 transactionID:kAnyTransactionID];
537 // Note that AESendMessage effectively ignores kAEDefaultTimeout, because this
538 // call does not pass kAEWantReceipt (which is deprecated and unsupported on
539 // Mac). Instead, rely on OnPingChromeTimeout().
540 OSStatus status = AESendMessage(
541 [initial_event aeDesc], &replyEvent_, kAEQueueReply, kAEDefaultTimeout);
542 if (status != noErr) {
543 OSSTATUS_LOG(ERROR, status) << "AESendMessage";
544 [self closeWithSuccess:false];
548 - (void)message:(NSAppleEventDescriptor*)event
549 withReply:(NSAppleEventDescriptor*)reply {
550 [self closeWithSuccess:true];
553 - (void)closeWithSuccess:(bool)success {
554 onReply_.Run(success);
555 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
556 [em removeEventHandlerForEventClass:'aevt' andEventID:'ansr'];
561 //-----------------------------------------------------------------------------
565 // |ChromeAppModeStart()| is the point of entry into the framework from the app
567 __attribute__((visibility("default")))
568 int ChromeAppModeStart(const app_mode::ChromeAppModeInfo* info);
572 int ChromeAppModeStart(const app_mode::ChromeAppModeInfo* info) {
573 base::CommandLine::Init(info->argc, info->argv);
575 base::mac::ScopedNSAutoreleasePool scoped_pool;
576 base::AtExitManager exit_manager;
577 chrome::RegisterPathProvider();
579 if (info->major_version < app_mode::kCurrentChromeAppModeInfoMajorVersion) {
580 RAW_LOG(ERROR, "App Mode Loader too old.");
583 if (info->major_version > app_mode::kCurrentChromeAppModeInfoMajorVersion) {
584 RAW_LOG(ERROR, "Browser Framework too old to load App Shortcut.");
590 // Set bundle paths. This loads the bundles.
591 base::mac::SetOverrideOuterBundlePath(g_info->chrome_outer_bundle_path);
592 base::mac::SetOverrideFrameworkBundlePath(
593 g_info->chrome_versioned_path.Append(chrome::kFrameworkName));
595 // Calculate the preferred locale used by Chrome.
596 // We can't use l10n_util::OverrideLocaleWithCocoaLocale() because it calls
597 // [base::mac::OuterBundle() preferredLocalizations] which gets localizations
598 // from the bundle of the running app (i.e. it is equivalent to
599 // [[NSBundle mainBundle] preferredLocalizations]) instead of the target
601 NSArray* preferred_languages = [NSLocale preferredLanguages];
602 NSArray* supported_languages = [base::mac::OuterBundle() localizations];
603 std::string preferred_localization;
604 for (NSString* language in preferred_languages) {
605 if ([supported_languages containsObject:language]) {
606 preferred_localization = base::SysNSStringToUTF8(language);
610 std::string locale = l10n_util::NormalizeLocale(
611 l10n_util::GetApplicationLocale(preferred_localization));
613 // Load localized strings.
614 ui::ResourceBundle::InitSharedInstanceWithLocale(
615 locale, NULL, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
617 // Launch the IO thread.
618 base::Thread::Options io_thread_options;
619 io_thread_options.message_loop_type = base::MessageLoop::TYPE_IO;
620 base::Thread *io_thread = new base::Thread("CrAppShimIO");
621 io_thread->StartWithOptions(io_thread_options);
622 g_io_thread = io_thread;
624 // Find already running instances of Chrome.
626 std::string chrome_process_id =
627 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
628 app_mode::kLaunchedByChromeProcessId);
629 if (!chrome_process_id.empty()) {
630 if (!base::StringToInt(chrome_process_id, &pid))
631 LOG(FATAL) << "Invalid PID: " << chrome_process_id;
633 NSString* chrome_bundle_id = [base::mac::OuterBundle() bundleIdentifier];
634 NSArray* existing_chrome = [NSRunningApplication
635 runningApplicationsWithBundleIdentifier:chrome_bundle_id];
636 if ([existing_chrome count] > 0)
637 pid = [[existing_chrome objectAtIndex:0] processIdentifier];
640 AppShimController controller;
641 base::MessageLoopForUI main_message_loop;
642 main_message_loop.set_thread_name("MainThread");
643 base::PlatformThread::SetName("CrAppShimMain");
645 // In tests, launching Chrome does nothing, and we won't get a ping response,
646 // so just assume the socket exists.
648 !base::CommandLine::ForCurrentProcess()->HasSwitch(
649 app_mode::kLaunchedForTest)) {
650 // Launch Chrome if it isn't already running.
651 ProcessSerialNumber psn;
652 base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
653 command_line.AppendSwitch(switches::kSilentLaunch);
655 // If the shim is the app launcher, pass --show-app-list when starting a new
656 // Chrome process to inform startup codepaths and load the correct profile.
657 if (info->app_mode_id == app_mode::kAppListModeId) {
658 command_line.AppendSwitch(switches::kShowAppList);
660 command_line.AppendSwitchPath(switches::kProfileDirectory,
665 base::mac::OpenApplicationWithPath(base::mac::OuterBundlePath(),
672 base::Callback<void(bool)> on_ping_chrome_reply =
673 base::Bind(&AppShimController::OnPingChromeReply,
674 base::Unretained(&controller));
676 // This code abuses the fact that Apple Events sent before the process is
677 // fully initialized don't receive a reply until its run loop starts. Once
678 // the reply is received, Chrome will have opened its IPC port, guaranteed.
679 [ReplyEventHandler pingProcess:psn
680 andCall:on_ping_chrome_reply];
682 main_message_loop.PostDelayedTask(
684 base::Bind(&AppShimController::OnPingChromeTimeout,
685 base::Unretained(&controller)),
686 base::TimeDelta::FromSeconds(kPingChromeTimeoutSeconds));
688 // Chrome already running. Proceed to init. This could still fail if Chrome
689 // is still starting up or shutting down, but the process will exit quickly,
690 // which is preferable to waiting for the Apple Event to timeout after one
692 main_message_loop.PostTask(
694 base::Bind(&AppShimController::Init,
695 base::Unretained(&controller)));
698 main_message_loop.Run();