platform_util_mac.mm 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. // Copyright (c) 2013 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "atom/common/platform_util.h"
  5. #import <Carbon/Carbon.h>
  6. #import <Cocoa/Cocoa.h>
  7. #import <ServiceManagement/ServiceManagement.h>
  8. #include "base/callback.h"
  9. #include "base/files/file_path.h"
  10. #include "base/files/file_util.h"
  11. #include "base/logging.h"
  12. #include "base/mac/foundation_util.h"
  13. #include "base/mac/mac_logging.h"
  14. #include "base/mac/scoped_aedesc.h"
  15. #include "base/strings/stringprintf.h"
  16. #include "base/strings/sys_string_conversions.h"
  17. #include "net/base/mac/url_conversions.h"
  18. #include "url/gurl.h"
  19. namespace {
  20. std::string MessageForOSStatus(OSStatus status, const char* default_message) {
  21. switch (status) {
  22. case kLSAppInTrashErr:
  23. return "The application cannot be run because it is inside a Trash "
  24. "folder.";
  25. case kLSUnknownErr:
  26. return "An unknown error has occurred.";
  27. case kLSNotAnApplicationErr:
  28. return "The item to be registered is not an application.";
  29. case kLSNotInitializedErr:
  30. return "Formerly returned by LSInit on initialization failure; "
  31. "no longer used.";
  32. case kLSDataUnavailableErr:
  33. return "Data of the desired type is not available (for example, there is "
  34. "no kind string).";
  35. case kLSApplicationNotFoundErr:
  36. return "No application in the Launch Services database matches the input "
  37. "criteria.";
  38. case kLSDataErr:
  39. return "Data is structured improperly (for example, an item’s "
  40. "information property list is malformed). Not used in macOS 10.4.";
  41. case kLSLaunchInProgressErr:
  42. return "A launch of the application is already in progress.";
  43. case kLSServerCommunicationErr:
  44. return "There is a problem communicating with the server process that "
  45. "maintains the Launch Services database.";
  46. case kLSCannotSetInfoErr:
  47. return "The filename extension to be hidden cannot be hidden.";
  48. case kLSIncompatibleSystemVersionErr:
  49. return "The application to be launched cannot run on the current Mac OS "
  50. "version.";
  51. case kLSNoLaunchPermissionErr:
  52. return "The user does not have permission to launch the application (on a"
  53. "managed network).";
  54. case kLSNoExecutableErr:
  55. return "The executable file is missing or has an unusable format.";
  56. case kLSNoClassicEnvironmentErr:
  57. return "The Classic emulation environment was required but is not "
  58. "available.";
  59. case kLSMultipleSessionsNotSupportedErr:
  60. return "The application to be launched cannot run simultaneously in two "
  61. "different user sessions.";
  62. default:
  63. return base::StringPrintf("%s (%d)", default_message, status);
  64. }
  65. }
  66. // This may be called from a global dispatch queue, the methods used here are
  67. // thread safe, including LSGetApplicationForURL (> 10.2) and
  68. // NSWorkspace#openURLs.
  69. std::string OpenURL(NSURL* ns_url, bool activate) {
  70. CFURLRef openingApp = nullptr;
  71. OSStatus status = LSGetApplicationForURL(base::mac::NSToCFCast(ns_url),
  72. kLSRolesAll, nullptr, &openingApp);
  73. if (status != noErr)
  74. return MessageForOSStatus(status, "Failed to open");
  75. CFRelease(openingApp); // NOT A BUG; LSGetApplicationForURL retains for us
  76. NSUInteger launchOptions = NSWorkspaceLaunchDefault;
  77. if (!activate)
  78. launchOptions |= NSWorkspaceLaunchWithoutActivation;
  79. bool opened = [[NSWorkspace sharedWorkspace] openURLs:@[ ns_url ]
  80. withAppBundleIdentifier:nil
  81. options:launchOptions
  82. additionalEventParamDescriptor:nil
  83. launchIdentifiers:nil];
  84. if (!opened)
  85. return "Failed to open URL";
  86. return "";
  87. }
  88. NSString* GetLoginHelperBundleIdentifier() {
  89. return [[[NSBundle mainBundle] bundleIdentifier]
  90. stringByAppendingString:@".loginhelper"];
  91. }
  92. } // namespace
  93. namespace platform_util {
  94. bool ShowItemInFolder(const base::FilePath& path) {
  95. // The API only takes absolute path.
  96. base::FilePath full_path =
  97. path.IsAbsolute() ? path : base::MakeAbsoluteFilePath(path);
  98. DCHECK([NSThread isMainThread]);
  99. NSString* path_string = base::SysUTF8ToNSString(full_path.value());
  100. if (!path_string || ![[NSWorkspace sharedWorkspace] selectFile:path_string
  101. inFileViewerRootedAtPath:@""]) {
  102. LOG(WARNING) << "NSWorkspace failed to select file " << full_path.value();
  103. return false;
  104. }
  105. return true;
  106. }
  107. bool OpenItem(const base::FilePath& full_path) {
  108. DCHECK([NSThread isMainThread]);
  109. NSString* path_string = base::SysUTF8ToNSString(full_path.value());
  110. if (!path_string)
  111. return false;
  112. NSURL* url = [NSURL fileURLWithPath:path_string];
  113. if (!url)
  114. return false;
  115. const NSWorkspaceLaunchOptions launch_options =
  116. NSWorkspaceLaunchAsync | NSWorkspaceLaunchWithErrorPresentation;
  117. return [[NSWorkspace sharedWorkspace] openURLs:@[ url ]
  118. withAppBundleIdentifier:nil
  119. options:launch_options
  120. additionalEventParamDescriptor:nil
  121. launchIdentifiers:NULL];
  122. }
  123. bool OpenExternal(const GURL& url, bool activate) {
  124. DCHECK([NSThread isMainThread]);
  125. NSURL* ns_url = net::NSURLWithGURL(url);
  126. if (ns_url)
  127. return OpenURL(ns_url, activate).empty();
  128. return false;
  129. }
  130. void OpenExternal(const GURL& url,
  131. bool activate,
  132. const OpenExternalCallback& callback) {
  133. NSURL* ns_url = net::NSURLWithGURL(url);
  134. if (!ns_url) {
  135. callback.Run("Invalid URL");
  136. return;
  137. }
  138. __block OpenExternalCallback c = callback;
  139. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
  140. ^{
  141. __block std::string error = OpenURL(ns_url, activate);
  142. dispatch_async(dispatch_get_main_queue(), ^{
  143. c.Run(error);
  144. });
  145. });
  146. }
  147. bool MoveItemToTrash(const base::FilePath& full_path) {
  148. NSString* path_string = base::SysUTF8ToNSString(full_path.value());
  149. BOOL status = [[NSFileManager defaultManager]
  150. trashItemAtURL:[NSURL fileURLWithPath:path_string]
  151. resultingItemURL:nil
  152. error:nil];
  153. if (!path_string || !status)
  154. LOG(WARNING) << "NSWorkspace failed to move file " << full_path.value()
  155. << " to trash";
  156. return status;
  157. }
  158. void Beep() {
  159. NSBeep();
  160. }
  161. bool GetLoginItemEnabled() {
  162. BOOL enabled = NO;
  163. // SMJobCopyDictionary does not work in sandbox (see rdar://13626319)
  164. CFArrayRef jobs = SMCopyAllJobDictionaries(kSMDomainUserLaunchd);
  165. NSArray* jobs_ = CFBridgingRelease(jobs);
  166. NSString* identifier = GetLoginHelperBundleIdentifier();
  167. if (jobs_ && [jobs_ count] > 0) {
  168. for (NSDictionary* job in jobs_) {
  169. if ([identifier isEqualToString:[job objectForKey:@"Label"]]) {
  170. enabled = [[job objectForKey:@"OnDemand"] boolValue];
  171. break;
  172. }
  173. }
  174. }
  175. return enabled;
  176. }
  177. void SetLoginItemEnabled(bool enabled) {
  178. NSString* identifier = GetLoginHelperBundleIdentifier();
  179. SMLoginItemSetEnabled((__bridge CFStringRef)identifier, enabled);
  180. }
  181. } // namespace platform_util