platform_util_mac.mm 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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/files/file_path.h"
  11. #include "base/files/file_util.h"
  12. #include "base/functional/callback.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. bool MoveItemToTrashWithError(const base::FilePath& full_path,
  100. bool delete_on_fail,
  101. std::string* error) {
  102. NSString* path_string = base::SysUTF8ToNSString(full_path.value());
  103. if (!path_string) {
  104. *error = "Invalid file path: " + full_path.value();
  105. LOG(WARNING) << *error;
  106. return false;
  107. }
  108. NSURL* url = [NSURL fileURLWithPath:path_string];
  109. NSError* err = nil;
  110. BOOL did_trash = [[NSFileManager defaultManager] trashItemAtURL:url
  111. resultingItemURL:nil
  112. error:&err];
  113. if (delete_on_fail) {
  114. // Some volumes may not support a Trash folder or it may be disabled
  115. // so these methods will report failure by returning NO or nil and
  116. // an NSError with NSFeatureUnsupportedError.
  117. // Handle this by deleting the item as a fallback.
  118. if (!did_trash && [err code] == NSFeatureUnsupportedError) {
  119. did_trash = [[NSFileManager defaultManager] removeItemAtURL:url
  120. error:&err];
  121. }
  122. }
  123. if (!did_trash) {
  124. *error = base::SysNSStringToUTF8([err localizedDescription]);
  125. LOG(WARNING) << "NSWorkspace failed to move file " << full_path.value()
  126. << " to trash: " << *error;
  127. }
  128. return did_trash;
  129. }
  130. namespace internal {
  131. bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) {
  132. return MoveItemToTrashWithError(full_path, false, error);
  133. }
  134. } // namespace internal
  135. void Beep() {
  136. NSBeep();
  137. }
  138. bool GetLoginItemEnabled() {
  139. BOOL enabled = NO;
  140. #pragma clang diagnostic push
  141. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  142. // SMJobCopyDictionary does not work in sandbox (see rdar://13626319)
  143. CFArrayRef jobs = SMCopyAllJobDictionaries(kSMDomainUserLaunchd);
  144. #pragma clang diagnostic pop
  145. NSArray* jobs_ = CFBridgingRelease(jobs);
  146. NSString* identifier = GetLoginHelperBundleIdentifier();
  147. if (jobs_ && [jobs_ count] > 0) {
  148. for (NSDictionary* job in jobs_) {
  149. if ([identifier isEqualToString:[job objectForKey:@"Label"]]) {
  150. enabled = [[job objectForKey:@"OnDemand"] boolValue];
  151. break;
  152. }
  153. }
  154. }
  155. return enabled;
  156. }
  157. bool SetLoginItemEnabled(bool enabled) {
  158. NSString* identifier = GetLoginHelperBundleIdentifier();
  159. return SMLoginItemSetEnabled((__bridge CFStringRef)identifier, enabled);
  160. }
  161. } // namespace platform_util