platform_util_mac.mm 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 "shell/common/platform_util.h"
  5. #include <string>
  6. #include <utility>
  7. #import <Carbon/Carbon.h>
  8. #import <Cocoa/Cocoa.h>
  9. #import <ServiceManagement/ServiceManagement.h>
  10. #include "base/callback.h"
  11. #include "base/files/file_path.h"
  12. #include "base/files/file_util.h"
  13. #include "base/logging.h"
  14. #include "base/mac/foundation_util.h"
  15. #include "base/mac/mac_logging.h"
  16. #include "base/mac/scoped_aedesc.h"
  17. #include "base/strings/stringprintf.h"
  18. #include "base/strings/sys_string_conversions.h"
  19. #include "net/base/mac/url_conversions.h"
  20. #include "ui/views/widget/widget.h"
  21. #include "url/gurl.h"
  22. namespace {
  23. // This may be called from a global dispatch queue, the methods used here are
  24. // thread safe, including LSGetApplicationForURL (> 10.2) and
  25. // NSWorkspace#openURLs.
  26. std::string OpenURL(NSURL* ns_url, bool activate) {
  27. CFURLRef ref = LSCopyDefaultApplicationURLForURL(
  28. base::mac::NSToCFCast(ns_url), kLSRolesAll, nullptr);
  29. // If no application could be found, NULL is returned and outError
  30. // (if not NULL) is populated with kLSApplicationNotFoundErr.
  31. if (ref == NULL)
  32. return "No application in the Launch Services database matches the input "
  33. "criteria.";
  34. NSUInteger launchOptions = NSWorkspaceLaunchDefault;
  35. if (!activate)
  36. launchOptions |= NSWorkspaceLaunchWithoutActivation;
  37. bool opened = [[NSWorkspace sharedWorkspace] openURLs:@[ ns_url ]
  38. withAppBundleIdentifier:nil
  39. options:launchOptions
  40. additionalEventParamDescriptor:nil
  41. launchIdentifiers:nil];
  42. if (!opened)
  43. return "Failed to open URL";
  44. return "";
  45. }
  46. NSString* GetLoginHelperBundleIdentifier() {
  47. return [[[NSBundle mainBundle] bundleIdentifier]
  48. stringByAppendingString:@".loginhelper"];
  49. }
  50. std::string OpenPathOnThread(const base::FilePath& full_path) {
  51. NSString* path_string = base::SysUTF8ToNSString(full_path.value());
  52. NSURL* url = [NSURL fileURLWithPath:path_string];
  53. if (!url)
  54. return "Invalid path";
  55. const NSWorkspaceLaunchOptions launch_options =
  56. NSWorkspaceLaunchAsync | NSWorkspaceLaunchWithErrorPresentation;
  57. BOOL success = [[NSWorkspace sharedWorkspace] openURLs:@[ url ]
  58. withAppBundleIdentifier:nil
  59. options:launch_options
  60. additionalEventParamDescriptor:nil
  61. launchIdentifiers:NULL];
  62. return success ? "" : "Failed to open path";
  63. }
  64. } // namespace
  65. namespace platform_util {
  66. void ShowItemInFolder(const base::FilePath& path) {
  67. // The API only takes absolute path.
  68. base::FilePath full_path =
  69. path.IsAbsolute() ? path : base::MakeAbsoluteFilePath(path);
  70. DCHECK([NSThread isMainThread]);
  71. NSString* path_string = base::SysUTF8ToNSString(full_path.value());
  72. if (!path_string || ![[NSWorkspace sharedWorkspace] selectFile:path_string
  73. inFileViewerRootedAtPath:@""]) {
  74. LOG(WARNING) << "NSWorkspace failed to select file " << full_path.value();
  75. }
  76. }
  77. void OpenPath(const base::FilePath& full_path, OpenCallback callback) {
  78. std::move(callback).Run(OpenPathOnThread(full_path));
  79. }
  80. void OpenExternal(const GURL& url,
  81. const OpenExternalOptions& options,
  82. OpenCallback callback) {
  83. DCHECK([NSThread isMainThread]);
  84. NSURL* ns_url = net::NSURLWithGURL(url);
  85. if (!ns_url) {
  86. std::move(callback).Run("Invalid URL");
  87. return;
  88. }
  89. bool activate = options.activate;
  90. __block OpenCallback c = std::move(callback);
  91. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
  92. ^{
  93. __block std::string error = OpenURL(ns_url, activate);
  94. dispatch_async(dispatch_get_main_queue(), ^{
  95. std::move(c).Run(error);
  96. });
  97. });
  98. }
  99. // The following function helps with debug builds on the Mac
  100. gfx::NativeView GetViewForWindow(gfx::NativeWindow native_window) {
  101. NOTREACHED();
  102. return nil;
  103. }
  104. // The following function helps with debug builds on the Mac
  105. gfx::NativeView GetParent(gfx::NativeView view) {
  106. NOTREACHED();
  107. return nil;
  108. }
  109. bool MoveItemToTrashWithError(const base::FilePath& full_path,
  110. bool delete_on_fail,
  111. std::string* error) {
  112. NSString* path_string = base::SysUTF8ToNSString(full_path.value());
  113. if (!path_string) {
  114. *error = "Invalid file path: " + full_path.value();
  115. LOG(WARNING) << *error;
  116. return false;
  117. }
  118. NSURL* url = [NSURL fileURLWithPath:path_string];
  119. NSError* err = nil;
  120. BOOL did_trash = [[NSFileManager defaultManager] trashItemAtURL:url
  121. resultingItemURL:nil
  122. error:&err];
  123. if (delete_on_fail) {
  124. // Some volumes may not support a Trash folder or it may be disabled
  125. // so these methods will report failure by returning NO or nil and
  126. // an NSError with NSFeatureUnsupportedError.
  127. // Handle this by deleting the item as a fallback.
  128. if (!did_trash && [err code] == NSFeatureUnsupportedError) {
  129. did_trash = [[NSFileManager defaultManager] removeItemAtURL:url
  130. error:&err];
  131. }
  132. }
  133. if (!did_trash) {
  134. *error = base::SysNSStringToUTF8([err localizedDescription]);
  135. LOG(WARNING) << "NSWorkspace failed to move file " << full_path.value()
  136. << " to trash: " << *error;
  137. }
  138. return did_trash;
  139. }
  140. namespace internal {
  141. bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) {
  142. return MoveItemToTrashWithError(full_path, false, error);
  143. }
  144. } // namespace internal
  145. void Beep() {
  146. NSBeep();
  147. }
  148. bool GetLoginItemEnabled() {
  149. BOOL enabled = NO;
  150. #pragma clang diagnostic push
  151. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  152. // SMJobCopyDictionary does not work in sandbox (see rdar://13626319)
  153. CFArrayRef jobs = SMCopyAllJobDictionaries(kSMDomainUserLaunchd);
  154. #pragma clang diagnostic pop
  155. NSArray* jobs_ = CFBridgingRelease(jobs);
  156. NSString* identifier = GetLoginHelperBundleIdentifier();
  157. if (jobs_ && [jobs_ count] > 0) {
  158. for (NSDictionary* job in jobs_) {
  159. if ([identifier isEqualToString:[job objectForKey:@"Label"]]) {
  160. enabled = [[job objectForKey:@"OnDemand"] boolValue];
  161. break;
  162. }
  163. }
  164. }
  165. return enabled;
  166. }
  167. bool SetLoginItemEnabled(bool enabled) {
  168. NSString* identifier = GetLoginHelperBundleIdentifier();
  169. return SMLoginItemSetEnabled((__bridge CFStringRef)identifier, enabled);
  170. }
  171. } // namespace platform_util