platform_util_mac.mm 6.1 KB

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