browser_mac.mm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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/browser/browser.h"
  5. #include <memory>
  6. #include <string>
  7. #include <utility>
  8. #include "base/mac/bundle_locations.h"
  9. #include "base/mac/foundation_util.h"
  10. #include "base/mac/mac_util.h"
  11. #include "base/mac/scoped_cftyperef.h"
  12. #include "base/strings/string_number_conversions.h"
  13. #include "base/strings/sys_string_conversions.h"
  14. #include "net/base/mac/url_conversions.h"
  15. #include "shell/browser/badging/badge_manager.h"
  16. #include "shell/browser/mac/dict_util.h"
  17. #include "shell/browser/mac/electron_application.h"
  18. #include "shell/browser/mac/electron_application_delegate.h"
  19. #include "shell/browser/native_window.h"
  20. #include "shell/browser/window_list.h"
  21. #include "shell/common/api/electron_api_native_image.h"
  22. #include "shell/common/application_info.h"
  23. #include "shell/common/gin_converters/image_converter.h"
  24. #include "shell/common/gin_helper/arguments.h"
  25. #include "shell/common/gin_helper/dictionary.h"
  26. #include "shell/common/gin_helper/error_thrower.h"
  27. #include "shell/common/gin_helper/promise.h"
  28. #include "shell/common/platform_util.h"
  29. #include "ui/gfx/image/image.h"
  30. #include "url/gurl.h"
  31. namespace electron {
  32. namespace {
  33. NSString* GetAppPathForProtocol(const GURL& url) {
  34. NSURL* ns_url = [NSURL
  35. URLWithString:base::SysUTF8ToNSString(url.possibly_invalid_spec())];
  36. base::ScopedCFTypeRef<CFErrorRef> out_err;
  37. base::ScopedCFTypeRef<CFURLRef> openingApp(LSCopyDefaultApplicationURLForURL(
  38. (CFURLRef)ns_url, kLSRolesAll, out_err.InitializeInto()));
  39. if (out_err) {
  40. // likely kLSApplicationNotFoundErr
  41. return nullptr;
  42. }
  43. NSString* app_path = [base::mac::CFToNSCast(openingApp.get()) path];
  44. return app_path;
  45. }
  46. gfx::Image GetApplicationIconForProtocol(NSString* _Nonnull app_path) {
  47. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile:app_path];
  48. gfx::Image icon(image);
  49. return icon;
  50. }
  51. std::u16string GetAppDisplayNameForProtocol(NSString* app_path) {
  52. NSString* app_display_name =
  53. [[NSFileManager defaultManager] displayNameAtPath:app_path];
  54. return base::SysNSStringToUTF16(app_display_name);
  55. }
  56. } // namespace
  57. v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol(
  58. v8::Isolate* isolate,
  59. const GURL& url) {
  60. gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
  61. v8::Local<v8::Promise> handle = promise.GetHandle();
  62. gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
  63. NSString* ns_app_path = GetAppPathForProtocol(url);
  64. if (!ns_app_path) {
  65. promise.RejectWithErrorMessage(
  66. "Unable to retrieve installation path to app");
  67. return handle;
  68. }
  69. std::u16string app_path = base::SysNSStringToUTF16(ns_app_path);
  70. std::u16string app_display_name = GetAppDisplayNameForProtocol(ns_app_path);
  71. gfx::Image app_icon = GetApplicationIconForProtocol(ns_app_path);
  72. dict.Set("name", app_display_name);
  73. dict.Set("path", app_path);
  74. dict.Set("icon", app_icon);
  75. promise.Resolve(dict);
  76. return handle;
  77. }
  78. void Browser::SetShutdownHandler(base::RepeatingCallback<bool()> handler) {
  79. [[AtomApplication sharedApplication] setShutdownHandler:std::move(handler)];
  80. }
  81. void Browser::Focus(gin::Arguments* args) {
  82. gin_helper::Dictionary opts;
  83. bool steal_focus = false;
  84. if (args->GetNext(&opts)) {
  85. gin_helper::ErrorThrower thrower(args->isolate());
  86. if (!opts.Get("steal", &steal_focus)) {
  87. thrower.ThrowError(
  88. "Expected options object to contain a 'steal' boolean property");
  89. return;
  90. }
  91. }
  92. [[AtomApplication sharedApplication] activateIgnoringOtherApps:steal_focus];
  93. }
  94. void Browser::Hide() {
  95. [[AtomApplication sharedApplication] hide:nil];
  96. }
  97. void Browser::Show() {
  98. [[AtomApplication sharedApplication] unhide:nil];
  99. }
  100. void Browser::AddRecentDocument(const base::FilePath& path) {
  101. NSString* path_string = base::mac::FilePathToNSString(path);
  102. if (!path_string)
  103. return;
  104. NSURL* u = [NSURL fileURLWithPath:path_string];
  105. if (!u)
  106. return;
  107. [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:u];
  108. }
  109. void Browser::ClearRecentDocuments() {
  110. [[NSDocumentController sharedDocumentController] clearRecentDocuments:nil];
  111. }
  112. bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol,
  113. gin::Arguments* args) {
  114. NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
  115. if (!identifier)
  116. return false;
  117. if (!Browser::IsDefaultProtocolClient(protocol, args))
  118. return false;
  119. NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
  120. CFStringRef protocol_cf = base::mac::NSToCFCast(protocol_ns);
  121. CFArrayRef bundleList = LSCopyAllHandlersForURLScheme(protocol_cf);
  122. if (!bundleList) {
  123. return false;
  124. }
  125. // On macOS, we can't query the default, but the handlers list seems to put
  126. // Apple's defaults first, so we'll use the first option that isn't our bundle
  127. CFStringRef other = nil;
  128. for (CFIndex i = 0; i < CFArrayGetCount(bundleList); ++i) {
  129. other =
  130. base::mac::CFCast<CFStringRef>(CFArrayGetValueAtIndex(bundleList, i));
  131. if (![identifier isEqualToString:(__bridge NSString*)other]) {
  132. break;
  133. }
  134. }
  135. // No other app was found set it to none instead of setting it back to itself.
  136. if ([identifier isEqualToString:(__bridge NSString*)other]) {
  137. other = base::mac::NSToCFCast(@"None");
  138. }
  139. OSStatus return_code = LSSetDefaultHandlerForURLScheme(protocol_cf, other);
  140. return return_code == noErr;
  141. }
  142. bool Browser::SetAsDefaultProtocolClient(const std::string& protocol,
  143. gin::Arguments* args) {
  144. if (protocol.empty())
  145. return false;
  146. NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
  147. if (!identifier)
  148. return false;
  149. NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
  150. OSStatus return_code = LSSetDefaultHandlerForURLScheme(
  151. base::mac::NSToCFCast(protocol_ns), base::mac::NSToCFCast(identifier));
  152. return return_code == noErr;
  153. }
  154. bool Browser::IsDefaultProtocolClient(const std::string& protocol,
  155. gin::Arguments* args) {
  156. if (protocol.empty())
  157. return false;
  158. NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
  159. if (!identifier)
  160. return false;
  161. NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
  162. base::ScopedCFTypeRef<CFStringRef> bundleId(
  163. LSCopyDefaultHandlerForURLScheme(base::mac::NSToCFCast(protocol_ns)));
  164. if (!bundleId)
  165. return false;
  166. // Ensure the comparison is case-insensitive
  167. // as LS does not persist the case of the bundle id.
  168. NSComparisonResult result =
  169. [base::mac::CFToNSCast(bundleId) caseInsensitiveCompare:identifier];
  170. return result == NSOrderedSame;
  171. }
  172. std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) {
  173. NSString* app_path = GetAppPathForProtocol(url);
  174. if (!app_path) {
  175. return std::u16string();
  176. }
  177. std::u16string app_display_name = GetAppDisplayNameForProtocol(app_path);
  178. return app_display_name;
  179. }
  180. bool Browser::SetBadgeCount(absl::optional<int> count) {
  181. DockSetBadgeText(!count.has_value() || count.value() != 0
  182. ? badging::BadgeManager::GetBadgeString(count)
  183. : "");
  184. if (count.has_value()) {
  185. badge_count_ = count.value();
  186. } else {
  187. badge_count_ = 0;
  188. }
  189. return true;
  190. }
  191. void Browser::SetUserActivity(const std::string& type,
  192. base::DictionaryValue user_info,
  193. gin::Arguments* args) {
  194. std::string url_string;
  195. args->GetNext(&url_string);
  196. [[AtomApplication sharedApplication]
  197. setCurrentActivity:base::SysUTF8ToNSString(type)
  198. withUserInfo:DictionaryValueToNSDictionary(user_info)
  199. withWebpageURL:net::NSURLWithGURL(GURL(url_string))];
  200. }
  201. std::string Browser::GetCurrentActivityType() {
  202. NSUserActivity* userActivity =
  203. [[AtomApplication sharedApplication] getCurrentActivity];
  204. return base::SysNSStringToUTF8(userActivity.activityType);
  205. }
  206. void Browser::InvalidateCurrentActivity() {
  207. [[AtomApplication sharedApplication] invalidateCurrentActivity];
  208. }
  209. void Browser::ResignCurrentActivity() {
  210. [[AtomApplication sharedApplication] resignCurrentActivity];
  211. }
  212. void Browser::UpdateCurrentActivity(const std::string& type,
  213. base::DictionaryValue user_info) {
  214. [[AtomApplication sharedApplication]
  215. updateCurrentActivity:base::SysUTF8ToNSString(type)
  216. withUserInfo:DictionaryValueToNSDictionary(user_info)];
  217. }
  218. bool Browser::WillContinueUserActivity(const std::string& type) {
  219. bool prevent_default = false;
  220. for (BrowserObserver& observer : observers_)
  221. observer.OnWillContinueUserActivity(&prevent_default, type);
  222. return prevent_default;
  223. }
  224. void Browser::DidFailToContinueUserActivity(const std::string& type,
  225. const std::string& error) {
  226. for (BrowserObserver& observer : observers_)
  227. observer.OnDidFailToContinueUserActivity(type, error);
  228. }
  229. bool Browser::ContinueUserActivity(const std::string& type,
  230. base::DictionaryValue user_info) {
  231. bool prevent_default = false;
  232. for (BrowserObserver& observer : observers_)
  233. observer.OnContinueUserActivity(&prevent_default, type, user_info);
  234. return prevent_default;
  235. }
  236. void Browser::UserActivityWasContinued(const std::string& type,
  237. base::DictionaryValue user_info) {
  238. for (BrowserObserver& observer : observers_)
  239. observer.OnUserActivityWasContinued(type, user_info);
  240. }
  241. bool Browser::UpdateUserActivityState(const std::string& type,
  242. base::DictionaryValue user_info) {
  243. bool prevent_default = false;
  244. for (BrowserObserver& observer : observers_)
  245. observer.OnUpdateUserActivityState(&prevent_default, type, user_info);
  246. return prevent_default;
  247. }
  248. Browser::LoginItemSettings Browser::GetLoginItemSettings(
  249. const LoginItemSettings& options) {
  250. LoginItemSettings settings;
  251. #if defined(MAS_BUILD)
  252. settings.open_at_login = platform_util::GetLoginItemEnabled();
  253. #else
  254. settings.open_at_login =
  255. base::mac::CheckLoginItemStatus(&settings.open_as_hidden);
  256. settings.restore_state = base::mac::WasLaunchedAsLoginItemRestoreState();
  257. settings.opened_at_login = base::mac::WasLaunchedAsLoginOrResumeItem();
  258. settings.opened_as_hidden = base::mac::WasLaunchedAsHiddenLoginItem();
  259. #endif
  260. return settings;
  261. }
  262. void RemoveFromLoginItems() {
  263. #pragma clang diagnostic push // https://crbug.com/1154377
  264. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  265. // logic to find the login item copied from GetLoginItemForApp in
  266. // base/mac/mac_util.mm
  267. base::ScopedCFTypeRef<LSSharedFileListRef> login_items(
  268. LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL));
  269. if (!login_items.get()) {
  270. LOG(ERROR) << "Couldn't get a Login Items list.";
  271. return;
  272. }
  273. base::scoped_nsobject<NSArray> login_items_array(
  274. base::mac::CFToNSCast(LSSharedFileListCopySnapshot(login_items, NULL)));
  275. NSURL* url = [NSURL fileURLWithPath:[base::mac::MainBundle() bundlePath]];
  276. for (NSUInteger i = 0; i < [login_items_array count]; ++i) {
  277. LSSharedFileListItemRef item =
  278. reinterpret_cast<LSSharedFileListItemRef>(login_items_array[i]);
  279. base::ScopedCFTypeRef<CFErrorRef> error;
  280. CFURLRef item_url_ref =
  281. LSSharedFileListItemCopyResolvedURL(item, 0, error.InitializeInto());
  282. if (!error && item_url_ref) {
  283. base::ScopedCFTypeRef<CFURLRef> item_url(item_url_ref);
  284. if (CFEqual(item_url, url)) {
  285. LSSharedFileListItemRemove(login_items, item);
  286. return;
  287. }
  288. }
  289. }
  290. #pragma clang diagnostic pop
  291. }
  292. void Browser::SetLoginItemSettings(LoginItemSettings settings) {
  293. #if defined(MAS_BUILD)
  294. if (!platform_util::SetLoginItemEnabled(settings.open_at_login)) {
  295. LOG(ERROR) << "Unable to set login item enabled on sandboxed app.";
  296. }
  297. #else
  298. if (settings.open_at_login) {
  299. base::mac::AddToLoginItems(settings.open_as_hidden);
  300. } else {
  301. RemoveFromLoginItems();
  302. }
  303. #endif
  304. }
  305. std::string Browser::GetExecutableFileVersion() const {
  306. return GetApplicationVersion();
  307. }
  308. std::string Browser::GetExecutableFileProductName() const {
  309. return GetApplicationName();
  310. }
  311. int Browser::DockBounce(BounceType type) {
  312. return [[AtomApplication sharedApplication]
  313. requestUserAttention:static_cast<NSRequestUserAttentionType>(type)];
  314. }
  315. void Browser::DockCancelBounce(int request_id) {
  316. [[AtomApplication sharedApplication] cancelUserAttentionRequest:request_id];
  317. }
  318. void Browser::DockSetBadgeText(const std::string& label) {
  319. NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
  320. [tile setBadgeLabel:base::SysUTF8ToNSString(label)];
  321. }
  322. void Browser::DockDownloadFinished(const std::string& filePath) {
  323. [[NSDistributedNotificationCenter defaultCenter]
  324. postNotificationName:@"com.apple.DownloadFileFinished"
  325. object:base::SysUTF8ToNSString(filePath)];
  326. }
  327. std::string Browser::DockGetBadgeText() {
  328. NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
  329. return base::SysNSStringToUTF8([tile badgeLabel]);
  330. }
  331. void Browser::DockHide() {
  332. // Transforming application state from UIElement to Foreground is an
  333. // asyncronous operation, and unfortunately there is currently no way to know
  334. // when it is finished.
  335. // So if we call DockHide => DockShow => DockHide => DockShow in a very short
  336. // time, we would triger a bug of macOS that, there would be multiple dock
  337. // icons of the app left in system.
  338. // To work around this, we make sure DockHide does nothing if it is called
  339. // immediately after DockShow. After some experiments, 1 second seems to be
  340. // a proper interval.
  341. if (!last_dock_show_.is_null() &&
  342. base::Time::Now() - last_dock_show_ < base::TimeDelta::FromSeconds(1)) {
  343. return;
  344. }
  345. for (auto* const& window : WindowList::GetWindows())
  346. [window->GetNativeWindow().GetNativeNSWindow() setCanHide:NO];
  347. ProcessSerialNumber psn = {0, kCurrentProcess};
  348. TransformProcessType(&psn, kProcessTransformToUIElementApplication);
  349. }
  350. bool Browser::DockIsVisible() {
  351. // Because DockShow has a slight delay this may not be true immediately
  352. // after that call.
  353. return ([[NSRunningApplication currentApplication] activationPolicy] ==
  354. NSApplicationActivationPolicyRegular);
  355. }
  356. v8::Local<v8::Promise> Browser::DockShow(v8::Isolate* isolate) {
  357. last_dock_show_ = base::Time::Now();
  358. gin_helper::Promise<void> promise(isolate);
  359. v8::Local<v8::Promise> handle = promise.GetHandle();
  360. BOOL active = [[NSRunningApplication currentApplication] isActive];
  361. ProcessSerialNumber psn = {0, kCurrentProcess};
  362. if (active) {
  363. // Workaround buggy behavior of TransformProcessType.
  364. // http://stackoverflow.com/questions/7596643/
  365. NSArray* runningApps = [NSRunningApplication
  366. runningApplicationsWithBundleIdentifier:@"com.apple.dock"];
  367. for (NSRunningApplication* app in runningApps) {
  368. [app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  369. break;
  370. }
  371. __block gin_helper::Promise<void> p = std::move(promise);
  372. dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
  373. dispatch_after(one_ms, dispatch_get_main_queue(), ^{
  374. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  375. dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
  376. dispatch_after(one_ms, dispatch_get_main_queue(), ^{
  377. [[NSRunningApplication currentApplication]
  378. activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  379. p.Resolve();
  380. });
  381. });
  382. } else {
  383. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  384. promise.Resolve();
  385. }
  386. return handle;
  387. }
  388. void Browser::DockSetMenu(ElectronMenuModel* model) {
  389. ElectronApplicationDelegate* delegate =
  390. (ElectronApplicationDelegate*)[NSApp delegate];
  391. [delegate setApplicationDockMenu:model];
  392. }
  393. void Browser::DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
  394. gfx::Image image;
  395. if (!icon->IsNull()) {
  396. api::NativeImage* native_image = nullptr;
  397. if (!api::NativeImage::TryConvertNativeImage(isolate, icon, &native_image))
  398. return;
  399. image = native_image->image();
  400. }
  401. [[AtomApplication sharedApplication]
  402. setApplicationIconImage:image.AsNSImage()];
  403. }
  404. void Browser::ShowAboutPanel() {
  405. NSDictionary* options = DictionaryValueToNSDictionary(about_panel_options_);
  406. // Credits must be a NSAttributedString instead of NSString
  407. NSString* credits = (NSString*)options[@"Credits"];
  408. if (credits != nil) {
  409. base::scoped_nsobject<NSMutableDictionary> mutable_options(
  410. [options mutableCopy]);
  411. base::scoped_nsobject<NSAttributedString> creditString(
  412. [[NSAttributedString alloc]
  413. initWithString:credits
  414. attributes:@{
  415. NSForegroundColorAttributeName : [NSColor textColor]
  416. }]);
  417. [mutable_options setValue:creditString forKey:@"Credits"];
  418. options = [NSDictionary dictionaryWithDictionary:mutable_options];
  419. }
  420. [[AtomApplication sharedApplication]
  421. orderFrontStandardAboutPanelWithOptions:options];
  422. }
  423. void Browser::SetAboutPanelOptions(base::DictionaryValue options) {
  424. about_panel_options_.Clear();
  425. for (const auto& pair : options.DictItems()) {
  426. std::string key = std::string(pair.first);
  427. if (!key.empty() && pair.second.is_string()) {
  428. key[0] = base::ToUpperASCII(key[0]);
  429. auto val = std::make_unique<base::Value>(pair.second.Clone());
  430. about_panel_options_.Set(key, std::move(val));
  431. }
  432. }
  433. }
  434. void Browser::ShowEmojiPanel() {
  435. [[AtomApplication sharedApplication] orderFrontCharacterPalette:nil];
  436. }
  437. bool Browser::IsEmojiPanelSupported() {
  438. return true;
  439. }
  440. bool Browser::IsSecureKeyboardEntryEnabled() {
  441. return password_input_enabler_.get() != nullptr;
  442. }
  443. void Browser::SetSecureKeyboardEntryEnabled(bool enabled) {
  444. if (enabled) {
  445. password_input_enabler_ =
  446. std::make_unique<ui::ScopedPasswordInputEnabler>();
  447. } else {
  448. password_input_enabler_.reset();
  449. }
  450. }
  451. } // namespace electron