platform_util_mac.mm 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. } // namespace
  50. namespace platform_util {
  51. void ShowItemInFolder(const base::FilePath& path) {
  52. // The API only takes absolute path.
  53. base::FilePath full_path =
  54. path.IsAbsolute() ? path : base::MakeAbsoluteFilePath(path);
  55. DCHECK([NSThread isMainThread]);
  56. NSString* path_string = base::SysUTF8ToNSString(full_path.value());
  57. if (!path_string || ![[NSWorkspace sharedWorkspace] selectFile:path_string
  58. inFileViewerRootedAtPath:@""]) {
  59. LOG(WARNING) << "NSWorkspace failed to select file " << full_path.value();
  60. }
  61. }
  62. bool OpenItem(const base::FilePath& full_path) {
  63. DCHECK([NSThread isMainThread]);
  64. NSString* path_string = base::SysUTF8ToNSString(full_path.value());
  65. if (!path_string)
  66. return false;
  67. NSURL* url = [NSURL fileURLWithPath:path_string];
  68. if (!url)
  69. return false;
  70. const NSWorkspaceLaunchOptions launch_options =
  71. NSWorkspaceLaunchAsync | NSWorkspaceLaunchWithErrorPresentation;
  72. return [[NSWorkspace sharedWorkspace] openURLs:@[ url ]
  73. withAppBundleIdentifier:nil
  74. options:launch_options
  75. additionalEventParamDescriptor:nil
  76. launchIdentifiers:NULL];
  77. }
  78. void OpenExternal(const GURL& url,
  79. const OpenExternalOptions& options,
  80. OpenExternalCallback callback) {
  81. DCHECK([NSThread isMainThread]);
  82. NSURL* ns_url = net::NSURLWithGURL(url);
  83. if (!ns_url) {
  84. std::move(callback).Run("Invalid URL");
  85. return;
  86. }
  87. bool activate = options.activate;
  88. __block OpenExternalCallback c = std::move(callback);
  89. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
  90. ^{
  91. __block std::string error = OpenURL(ns_url, activate);
  92. dispatch_async(dispatch_get_main_queue(), ^{
  93. std::move(c).Run(error);
  94. });
  95. });
  96. }
  97. bool MoveItemToTrash(const base::FilePath& full_path, bool delete_on_fail) {
  98. NSString* path_string = base::SysUTF8ToNSString(full_path.value());
  99. if (!path_string) {
  100. LOG(WARNING) << "Invalid file path " << full_path.value();
  101. return false;
  102. }
  103. NSURL* url = [NSURL fileURLWithPath:path_string];
  104. NSError* err = nil;
  105. BOOL did_trash = [[NSFileManager defaultManager] trashItemAtURL:url
  106. resultingItemURL:nil
  107. error:&err];
  108. if (delete_on_fail) {
  109. // Some volumes may not support a Trash folder or it may be disabled
  110. // so these methods will report failure by returning NO or nil and
  111. // an NSError with NSFeatureUnsupportedError.
  112. // Handle this by deleting the item as a fallback.
  113. if (!did_trash && [err code] == NSFeatureUnsupportedError) {
  114. did_trash = [[NSFileManager defaultManager] removeItemAtURL:url
  115. error:&err];
  116. }
  117. }
  118. if (!did_trash) {
  119. LOG(WARNING) << "NSWorkspace failed to move file " << full_path.value()
  120. << " to trash: "
  121. << base::SysNSStringToUTF8([err localizedDescription]);
  122. }
  123. return did_trash;
  124. }
  125. void Beep() {
  126. NSBeep();
  127. }
  128. bool GetLoginItemEnabled() {
  129. BOOL enabled = NO;
  130. #pragma clang diagnostic push
  131. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  132. // SMJobCopyDictionary does not work in sandbox (see rdar://13626319)
  133. CFArrayRef jobs = SMCopyAllJobDictionaries(kSMDomainUserLaunchd);
  134. #pragma clang diagnostic pop
  135. NSArray* jobs_ = CFBridgingRelease(jobs);
  136. NSString* identifier = GetLoginHelperBundleIdentifier();
  137. if (jobs_ && [jobs_ count] > 0) {
  138. for (NSDictionary* job in jobs_) {
  139. if ([identifier isEqualToString:[job objectForKey:@"Label"]]) {
  140. enabled = [[job objectForKey:@"OnDemand"] boolValue];
  141. break;
  142. }
  143. }
  144. }
  145. return enabled;
  146. }
  147. bool SetLoginItemEnabled(bool enabled) {
  148. NSString* identifier = GetLoginHelperBundleIdentifier();
  149. return SMLoginItemSetEnabled((__bridge CFStringRef)identifier, enabled);
  150. }
  151. } // namespace platform_util