platform_util_mac.mm 7.4 KB

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