browser_mac.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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/browser/browser.h"
  5. #include "atom/browser/mac/atom_application.h"
  6. #include "atom/browser/mac/atom_application_delegate.h"
  7. #include "atom/browser/mac/dict_util.h"
  8. #include "atom/browser/native_window.h"
  9. #include "atom/browser/window_list.h"
  10. #include "atom/common/platform_util.h"
  11. #include "base/mac/bundle_locations.h"
  12. #include "base/mac/foundation_util.h"
  13. #include "base/mac/mac_util.h"
  14. #include "base/strings/string_number_conversions.h"
  15. #include "base/strings/sys_string_conversions.h"
  16. #include "brightray/common/application_info.h"
  17. #include "net/base/mac/url_conversions.h"
  18. #include "ui/gfx/image/image.h"
  19. #include "url/gurl.h"
  20. namespace atom {
  21. void Browser::SetShutdownHandler(base::Callback<bool()> handler) {
  22. [[AtomApplication sharedApplication] setShutdownHandler:std::move(handler)];
  23. }
  24. void Browser::Focus() {
  25. [[AtomApplication sharedApplication] activateIgnoringOtherApps:YES];
  26. }
  27. void Browser::Hide() {
  28. [[AtomApplication sharedApplication] hide:nil];
  29. }
  30. void Browser::Show() {
  31. [[AtomApplication sharedApplication] unhide:nil];
  32. }
  33. void Browser::AddRecentDocument(const base::FilePath& path) {
  34. NSString* path_string = base::mac::FilePathToNSString(path);
  35. if (!path_string)
  36. return;
  37. NSURL* u = [NSURL fileURLWithPath:path_string];
  38. if (!u)
  39. return;
  40. [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:u];
  41. }
  42. void Browser::ClearRecentDocuments() {
  43. [[NSDocumentController sharedDocumentController] clearRecentDocuments:nil];
  44. }
  45. bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol,
  46. mate::Arguments* args) {
  47. NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
  48. if (!identifier)
  49. return false;
  50. if (!Browser::IsDefaultProtocolClient(protocol, args))
  51. return false;
  52. NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
  53. CFStringRef protocol_cf = base::mac::NSToCFCast(protocol_ns);
  54. CFArrayRef bundleList = LSCopyAllHandlersForURLScheme(protocol_cf);
  55. if (!bundleList) {
  56. return false;
  57. }
  58. // On macOS, we can't query the default, but the handlers list seems to put
  59. // Apple's defaults first, so we'll use the first option that isn't our bundle
  60. CFStringRef other = nil;
  61. for (CFIndex i = 0; i < CFArrayGetCount(bundleList); ++i) {
  62. other =
  63. base::mac::CFCast<CFStringRef>(CFArrayGetValueAtIndex(bundleList, i));
  64. if (![identifier isEqualToString:(__bridge NSString*)other]) {
  65. break;
  66. }
  67. }
  68. // No other app was found set it to none instead of setting it back to itself.
  69. if ([identifier isEqualToString:(__bridge NSString*)other]) {
  70. other = base::mac::NSToCFCast(@"None");
  71. }
  72. OSStatus return_code = LSSetDefaultHandlerForURLScheme(protocol_cf, other);
  73. return return_code == noErr;
  74. }
  75. bool Browser::SetAsDefaultProtocolClient(const std::string& protocol,
  76. mate::Arguments* args) {
  77. if (protocol.empty())
  78. return false;
  79. NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
  80. if (!identifier)
  81. return false;
  82. NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
  83. OSStatus return_code = LSSetDefaultHandlerForURLScheme(
  84. base::mac::NSToCFCast(protocol_ns), base::mac::NSToCFCast(identifier));
  85. return return_code == noErr;
  86. }
  87. bool Browser::IsDefaultProtocolClient(const std::string& protocol,
  88. mate::Arguments* args) {
  89. if (protocol.empty())
  90. return false;
  91. NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
  92. if (!identifier)
  93. return false;
  94. NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
  95. CFStringRef bundle =
  96. LSCopyDefaultHandlerForURLScheme(base::mac::NSToCFCast(protocol_ns));
  97. NSString* bundleId =
  98. static_cast<NSString*>(base::mac::CFTypeRefToNSObjectAutorelease(bundle));
  99. if (!bundleId)
  100. return false;
  101. // Ensure the comparison is case-insensitive
  102. // as LS does not persist the case of the bundle id.
  103. NSComparisonResult result = [bundleId caseInsensitiveCompare:identifier];
  104. return result == NSOrderedSame;
  105. }
  106. void Browser::SetAppUserModelID(const base::string16& name) {}
  107. bool Browser::SetBadgeCount(int count) {
  108. DockSetBadgeText(count != 0 ? base::IntToString(count) : "");
  109. badge_count_ = count;
  110. return true;
  111. }
  112. void Browser::SetUserActivity(const std::string& type,
  113. const base::DictionaryValue& user_info,
  114. mate::Arguments* args) {
  115. std::string url_string;
  116. args->GetNext(&url_string);
  117. [[AtomApplication sharedApplication]
  118. setCurrentActivity:base::SysUTF8ToNSString(type)
  119. withUserInfo:DictionaryValueToNSDictionary(user_info)
  120. withWebpageURL:net::NSURLWithGURL(GURL(url_string))];
  121. }
  122. std::string Browser::GetCurrentActivityType() {
  123. if (@available(macOS 10.10, *)) {
  124. NSUserActivity* userActivity =
  125. [[AtomApplication sharedApplication] getCurrentActivity];
  126. return base::SysNSStringToUTF8(userActivity.activityType);
  127. } else {
  128. return std::string();
  129. }
  130. }
  131. void Browser::InvalidateCurrentActivity() {
  132. [[AtomApplication sharedApplication] invalidateCurrentActivity];
  133. }
  134. void Browser::UpdateCurrentActivity(const std::string& type,
  135. const base::DictionaryValue& user_info) {
  136. [[AtomApplication sharedApplication]
  137. updateCurrentActivity:base::SysUTF8ToNSString(type)
  138. withUserInfo:DictionaryValueToNSDictionary(user_info)];
  139. }
  140. bool Browser::WillContinueUserActivity(const std::string& type) {
  141. bool prevent_default = false;
  142. for (BrowserObserver& observer : observers_)
  143. observer.OnWillContinueUserActivity(&prevent_default, type);
  144. return prevent_default;
  145. }
  146. void Browser::DidFailToContinueUserActivity(const std::string& type,
  147. const std::string& error) {
  148. for (BrowserObserver& observer : observers_)
  149. observer.OnDidFailToContinueUserActivity(type, error);
  150. }
  151. bool Browser::ContinueUserActivity(const std::string& type,
  152. const base::DictionaryValue& user_info) {
  153. bool prevent_default = false;
  154. for (BrowserObserver& observer : observers_)
  155. observer.OnContinueUserActivity(&prevent_default, type, user_info);
  156. return prevent_default;
  157. }
  158. void Browser::UserActivityWasContinued(const std::string& type,
  159. const base::DictionaryValue& user_info) {
  160. for (BrowserObserver& observer : observers_)
  161. observer.OnUserActivityWasContinued(type, user_info);
  162. }
  163. bool Browser::UpdateUserActivityState(const std::string& type,
  164. const base::DictionaryValue& user_info) {
  165. bool prevent_default = false;
  166. for (BrowserObserver& observer : observers_)
  167. observer.OnUpdateUserActivityState(&prevent_default, type, user_info);
  168. return prevent_default;
  169. }
  170. Browser::LoginItemSettings Browser::GetLoginItemSettings(
  171. const LoginItemSettings& options) {
  172. LoginItemSettings settings;
  173. #if defined(MAS_BUILD)
  174. settings.open_at_login = platform_util::GetLoginItemEnabled();
  175. #else
  176. settings.open_at_login =
  177. base::mac::CheckLoginItemStatus(&settings.open_as_hidden);
  178. settings.restore_state = base::mac::WasLaunchedAsLoginItemRestoreState();
  179. settings.opened_at_login = base::mac::WasLaunchedAsLoginOrResumeItem();
  180. settings.opened_as_hidden = base::mac::WasLaunchedAsHiddenLoginItem();
  181. #endif
  182. return settings;
  183. }
  184. // copied from GetLoginItemForApp in base/mac/mac_util.mm
  185. LSSharedFileListItemRef GetLoginItemForApp() {
  186. base::ScopedCFTypeRef<LSSharedFileListRef> login_items(
  187. LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL));
  188. if (!login_items.get()) {
  189. LOG(ERROR) << "Couldn't get a Login Items list.";
  190. return NULL;
  191. }
  192. base::scoped_nsobject<NSArray> login_items_array(
  193. base::mac::CFToNSCast(LSSharedFileListCopySnapshot(login_items, NULL)));
  194. NSURL* url = [NSURL fileURLWithPath:[base::mac::MainBundle() bundlePath]];
  195. for (NSUInteger i = 0; i < [login_items_array count]; ++i) {
  196. LSSharedFileListItemRef item =
  197. reinterpret_cast<LSSharedFileListItemRef>(login_items_array[i]);
  198. CFURLRef item_url_ref = NULL;
  199. if (LSSharedFileListItemResolve(item, 0, &item_url_ref, NULL) == noErr &&
  200. item_url_ref) {
  201. base::ScopedCFTypeRef<CFURLRef> item_url(item_url_ref);
  202. if (CFEqual(item_url, url)) {
  203. CFRetain(item);
  204. return item;
  205. }
  206. }
  207. }
  208. return NULL;
  209. }
  210. void RemoveFromLoginItems() {
  211. base::ScopedCFTypeRef<LSSharedFileListRef> list(
  212. LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL));
  213. if (!list) {
  214. LOG(ERROR) << "Unable to access shared file list";
  215. return;
  216. }
  217. if (GetLoginItemForApp() != NULL) {
  218. base::scoped_nsobject<NSArray> login_items_array(
  219. base::mac::CFToNSCast(LSSharedFileListCopySnapshot(list, NULL)));
  220. if (!login_items_array) {
  221. LOG(ERROR) << "No items in list of auto-loaded apps";
  222. return;
  223. }
  224. for (NSUInteger i = 0; i < [login_items_array count]; ++i) {
  225. LSSharedFileListItemRef item =
  226. reinterpret_cast<LSSharedFileListItemRef>(login_items_array[i]);
  227. CFURLRef url_ref = NULL;
  228. if (LSSharedFileListItemResolve(item, 0, &url_ref, NULL) == noErr &&
  229. item) {
  230. base::ScopedCFTypeRef<CFURLRef> url(url_ref);
  231. if ([[base::mac::CFToNSCast(url.get()) path]
  232. hasPrefix:[[NSBundle mainBundle] bundlePath]])
  233. LSSharedFileListItemRemove(list, item);
  234. }
  235. }
  236. }
  237. }
  238. void Browser::SetLoginItemSettings(LoginItemSettings settings) {
  239. #if defined(MAS_BUILD)
  240. platform_util::SetLoginItemEnabled(settings.open_at_login);
  241. #else
  242. if (settings.open_at_login)
  243. base::mac::AddToLoginItems(settings.open_as_hidden);
  244. else
  245. RemoveFromLoginItems();
  246. #endif
  247. }
  248. std::string Browser::GetExecutableFileVersion() const {
  249. return brightray::GetApplicationVersion();
  250. }
  251. std::string Browser::GetExecutableFileProductName() const {
  252. return brightray::GetApplicationName();
  253. }
  254. int Browser::DockBounce(BounceType type) {
  255. return [[AtomApplication sharedApplication]
  256. requestUserAttention:static_cast<NSRequestUserAttentionType>(type)];
  257. }
  258. void Browser::DockCancelBounce(int request_id) {
  259. [[AtomApplication sharedApplication] cancelUserAttentionRequest:request_id];
  260. }
  261. void Browser::DockSetBadgeText(const std::string& label) {
  262. NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
  263. [tile setBadgeLabel:base::SysUTF8ToNSString(label)];
  264. }
  265. void Browser::DockDownloadFinished(const std::string& filePath) {
  266. [[NSDistributedNotificationCenter defaultCenter]
  267. postNotificationName:@"com.apple.DownloadFileFinished"
  268. object:base::SysUTF8ToNSString(filePath)];
  269. }
  270. std::string Browser::DockGetBadgeText() {
  271. NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
  272. return base::SysNSStringToUTF8([tile badgeLabel]);
  273. }
  274. void Browser::DockHide() {
  275. for (auto* const& window : WindowList::GetWindows())
  276. [window->GetNativeWindow() setCanHide:NO];
  277. ProcessSerialNumber psn = {0, kCurrentProcess};
  278. TransformProcessType(&psn, kProcessTransformToUIElementApplication);
  279. }
  280. bool Browser::DockIsVisible() {
  281. // Because DockShow has a slight delay this may not be true immediately
  282. // after that call.
  283. return ([[NSRunningApplication currentApplication] activationPolicy] ==
  284. NSApplicationActivationPolicyRegular);
  285. }
  286. void Browser::DockShow() {
  287. BOOL active = [[NSRunningApplication currentApplication] isActive];
  288. ProcessSerialNumber psn = {0, kCurrentProcess};
  289. if (active) {
  290. // Workaround buggy behavior of TransformProcessType.
  291. // http://stackoverflow.com/questions/7596643/
  292. NSArray* runningApps = [NSRunningApplication
  293. runningApplicationsWithBundleIdentifier:@"com.apple.dock"];
  294. for (NSRunningApplication* app in runningApps) {
  295. [app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  296. break;
  297. }
  298. dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
  299. dispatch_after(one_ms, dispatch_get_main_queue(), ^{
  300. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  301. dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
  302. dispatch_after(one_ms, dispatch_get_main_queue(), ^{
  303. [[NSRunningApplication currentApplication]
  304. activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  305. });
  306. });
  307. } else {
  308. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  309. }
  310. }
  311. void Browser::DockSetMenu(AtomMenuModel* model) {
  312. AtomApplicationDelegate* delegate =
  313. (AtomApplicationDelegate*)[NSApp delegate];
  314. [delegate setApplicationDockMenu:model];
  315. }
  316. void Browser::DockSetIcon(const gfx::Image& image) {
  317. [[AtomApplication sharedApplication]
  318. setApplicationIconImage:image.AsNSImage()];
  319. }
  320. void Browser::ShowAboutPanel() {
  321. NSDictionary* options = DictionaryValueToNSDictionary(about_panel_options_);
  322. // Credits must be a NSAttributedString instead of NSString
  323. id credits = options[@"Credits"];
  324. if (credits != nil) {
  325. NSMutableDictionary* mutable_options = [options mutableCopy];
  326. mutable_options[@"Credits"] = [[[NSAttributedString alloc]
  327. initWithString:(NSString*)credits] autorelease];
  328. options = [NSDictionary dictionaryWithDictionary:mutable_options];
  329. }
  330. [[AtomApplication sharedApplication]
  331. orderFrontStandardAboutPanelWithOptions:options];
  332. }
  333. void Browser::SetAboutPanelOptions(const base::DictionaryValue& options) {
  334. about_panel_options_.Clear();
  335. // Upper case option keys for orderFrontStandardAboutPanelWithOptions format
  336. for (base::DictionaryValue::Iterator iter(options); !iter.IsAtEnd();
  337. iter.Advance()) {
  338. std::string key = iter.key();
  339. std::string value;
  340. if (!key.empty() && iter.value().GetAsString(&value)) {
  341. key[0] = base::ToUpperASCII(key[0]);
  342. about_panel_options_.SetString(key, value);
  343. }
  344. }
  345. }
  346. } // namespace atom