browser_mac.mm 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. #import <ServiceManagement/ServiceManagement.h>
  9. #include "base/apple/bridging.h"
  10. #include "base/apple/bundle_locations.h"
  11. #include "base/apple/scoped_cftyperef.h"
  12. #include "base/i18n/rtl.h"
  13. #include "base/mac/mac_util.h"
  14. #include "base/mac/mac_util.mm"
  15. #include "base/strings/sys_string_conversions.h"
  16. #include "chrome/browser/browser_process.h"
  17. #include "electron/mas.h"
  18. #include "net/base/apple/url_conversions.h"
  19. #include "shell/browser/badging/badge_manager.h"
  20. #include "shell/browser/browser_observer.h"
  21. #include "shell/browser/javascript_environment.h"
  22. #include "shell/browser/mac/dict_util.h"
  23. #include "shell/browser/mac/electron_application.h"
  24. #include "shell/browser/mac/electron_application_delegate.h"
  25. #include "shell/browser/native_window.h"
  26. #include "shell/browser/window_list.h"
  27. #include "shell/common/api/electron_api_native_image.h"
  28. #include "shell/common/application_info.h"
  29. #include "shell/common/gin_converters/image_converter.h"
  30. #include "shell/common/gin_converters/login_item_settings_converter.h"
  31. #include "shell/common/gin_helper/dictionary.h"
  32. #include "shell/common/gin_helper/error_thrower.h"
  33. #include "shell/common/gin_helper/promise.h"
  34. #include "shell/common/platform_util.h"
  35. #include "ui/base/resource/resource_scale_factor.h"
  36. #include "ui/gfx/image/image.h"
  37. #include "url/gurl.h"
  38. namespace electron {
  39. namespace {
  40. NSString* GetAppPathForProtocol(const GURL& url) {
  41. NSURL* ns_url = [NSURL
  42. URLWithString:base::SysUTF8ToNSString(url.possibly_invalid_spec())];
  43. base::apple::ScopedCFTypeRef<CFErrorRef> out_err;
  44. base::apple::ScopedCFTypeRef<CFURLRef> openingApp(
  45. LSCopyDefaultApplicationURLForURL(base::apple::NSToCFPtrCast(ns_url),
  46. kLSRolesAll, out_err.InitializeInto()));
  47. if (out_err) {
  48. // likely kLSApplicationNotFoundErr
  49. return nullptr;
  50. }
  51. NSString* app_path = [base::apple::CFToNSPtrCast(openingApp.get()) path];
  52. return app_path;
  53. }
  54. gfx::Image GetApplicationIconForProtocol(NSString* _Nonnull app_path) {
  55. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile:app_path];
  56. gfx::Image icon(image);
  57. return icon;
  58. }
  59. std::u16string GetAppDisplayNameForProtocol(NSString* app_path) {
  60. NSString* app_display_name =
  61. [[NSFileManager defaultManager] displayNameAtPath:app_path];
  62. return base::SysNSStringToUTF16(app_display_name);
  63. }
  64. #if !IS_MAS_BUILD()
  65. bool CheckLoginItemStatus(bool* is_hidden) {
  66. base::mac::LoginItemsFileList login_items;
  67. if (!login_items.Initialize())
  68. return false;
  69. base::apple::ScopedCFTypeRef<LSSharedFileListItemRef> item(
  70. login_items.GetLoginItemForMainApp());
  71. if (!item.get())
  72. return false;
  73. if (is_hidden)
  74. *is_hidden = base::mac::IsHiddenLoginItem(item.get());
  75. return true;
  76. }
  77. LoginItemSettings GetLoginItemSettingsDeprecated() {
  78. LoginItemSettings settings;
  79. settings.open_at_login = CheckLoginItemStatus(&settings.open_as_hidden);
  80. settings.restore_state = base::mac::WasLaunchedAsLoginItemRestoreState();
  81. settings.opened_at_login = base::mac::WasLaunchedAsLoginOrResumeItem();
  82. settings.opened_as_hidden = base::mac::WasLaunchedAsHiddenLoginItem();
  83. return settings;
  84. }
  85. #endif
  86. } // namespace
  87. v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol(
  88. v8::Isolate* isolate,
  89. const GURL& url) {
  90. gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
  91. v8::Local<v8::Promise> handle = promise.GetHandle();
  92. auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
  93. NSString* ns_app_path = GetAppPathForProtocol(url);
  94. if (!ns_app_path) {
  95. promise.RejectWithErrorMessage(
  96. "Unable to retrieve installation path to app");
  97. return handle;
  98. }
  99. std::u16string app_path = base::SysNSStringToUTF16(ns_app_path);
  100. std::u16string app_display_name = GetAppDisplayNameForProtocol(ns_app_path);
  101. gfx::Image app_icon = GetApplicationIconForProtocol(ns_app_path);
  102. dict.Set("name", app_display_name);
  103. dict.Set("path", app_path);
  104. dict.Set("icon", app_icon);
  105. promise.Resolve(dict);
  106. return handle;
  107. }
  108. void Browser::SetShutdownHandler(base::RepeatingCallback<bool()> handler) {
  109. [[AtomApplication sharedApplication] setShutdownHandler:std::move(handler)];
  110. }
  111. void Browser::Focus(gin::Arguments* args) {
  112. gin_helper::Dictionary opts;
  113. bool steal_focus = false;
  114. if (args->GetNext(&opts)) {
  115. gin_helper::ErrorThrower thrower(args->isolate());
  116. if (!opts.Get("steal", &steal_focus)) {
  117. thrower.ThrowError(
  118. "Expected options object to contain a 'steal' boolean property");
  119. return;
  120. }
  121. }
  122. [[AtomApplication sharedApplication] activateIgnoringOtherApps:steal_focus];
  123. }
  124. void Browser::Hide() {
  125. [[AtomApplication sharedApplication] hide:nil];
  126. }
  127. bool Browser::IsHidden() {
  128. return [[AtomApplication sharedApplication] isHidden];
  129. }
  130. void Browser::Show() {
  131. [[AtomApplication sharedApplication] unhide:nil];
  132. }
  133. void Browser::AddRecentDocument(const base::FilePath& path) {
  134. NSString* path_string = base::apple::FilePathToNSString(path);
  135. if (!path_string)
  136. return;
  137. NSURL* u = [NSURL fileURLWithPath:path_string];
  138. if (!u)
  139. return;
  140. [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:u];
  141. }
  142. void Browser::ClearRecentDocuments() {
  143. [[NSDocumentController sharedDocumentController] clearRecentDocuments:nil];
  144. }
  145. bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol,
  146. gin::Arguments* args) {
  147. NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
  148. if (!identifier)
  149. return false;
  150. if (!Browser::IsDefaultProtocolClient(protocol, args))
  151. return false;
  152. NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
  153. CFStringRef protocol_cf = base::apple::NSToCFPtrCast(protocol_ns);
  154. // TODO(codebytere): Use -[NSWorkspace URLForApplicationToOpenURL:] instead
  155. #pragma clang diagnostic push
  156. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  157. CFArrayRef bundleList = LSCopyAllHandlersForURLScheme(protocol_cf);
  158. #pragma clang diagnostic pop
  159. if (!bundleList) {
  160. return false;
  161. }
  162. // On macOS, we can't query the default, but the handlers list seems to put
  163. // Apple's defaults first, so we'll use the first option that isn't our bundle
  164. CFStringRef other = nil;
  165. for (CFIndex i = 0; i < CFArrayGetCount(bundleList); ++i) {
  166. other =
  167. base::apple::CFCast<CFStringRef>(CFArrayGetValueAtIndex(bundleList, i));
  168. if (![identifier isEqualToString:(__bridge NSString*)other]) {
  169. break;
  170. }
  171. }
  172. // No other app was found set it to none instead of setting it back to itself.
  173. if ([identifier isEqualToString:(__bridge NSString*)other]) {
  174. other = base::apple::NSToCFPtrCast(@"None");
  175. }
  176. OSStatus return_code = LSSetDefaultHandlerForURLScheme(protocol_cf, other);
  177. return return_code == noErr;
  178. }
  179. bool Browser::SetAsDefaultProtocolClient(const std::string& protocol,
  180. gin::Arguments* args) {
  181. if (protocol.empty())
  182. return false;
  183. NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
  184. if (!identifier)
  185. return false;
  186. NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
  187. OSStatus return_code =
  188. LSSetDefaultHandlerForURLScheme(base::apple::NSToCFPtrCast(protocol_ns),
  189. base::apple::NSToCFPtrCast(identifier));
  190. return return_code == noErr;
  191. }
  192. bool Browser::IsDefaultProtocolClient(const std::string& protocol,
  193. gin::Arguments* args) {
  194. if (protocol.empty())
  195. return false;
  196. NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
  197. if (!identifier)
  198. return false;
  199. NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
  200. // TODO(codebytere): Use -[NSWorkspace URLForApplicationToOpenURL:] instead
  201. #pragma clang diagnostic push
  202. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  203. base::apple::ScopedCFTypeRef<CFStringRef> bundleId(
  204. LSCopyDefaultHandlerForURLScheme(
  205. base::apple::NSToCFPtrCast(protocol_ns)));
  206. #pragma clang diagnostic pop
  207. if (!bundleId)
  208. return false;
  209. // Ensure the comparison is case-insensitive
  210. // as LS does not persist the case of the bundle id.
  211. NSComparisonResult result = [base::apple::CFToNSPtrCast(bundleId.get())
  212. caseInsensitiveCompare:identifier];
  213. return result == NSOrderedSame;
  214. }
  215. std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) {
  216. NSString* app_path = GetAppPathForProtocol(url);
  217. if (!app_path) {
  218. return std::u16string();
  219. }
  220. std::u16string app_display_name = GetAppDisplayNameForProtocol(app_path);
  221. return app_display_name;
  222. }
  223. bool Browser::SetBadgeCount(std::optional<int> count) {
  224. DockSetBadgeText(!count.has_value() || count.value() != 0
  225. ? badging::BadgeManager::GetBadgeString(count)
  226. : "");
  227. if (count.has_value()) {
  228. badge_count_ = count.value();
  229. } else {
  230. badge_count_ = 0;
  231. }
  232. return true;
  233. }
  234. void Browser::SetUserActivity(const std::string& type,
  235. base::Value::Dict user_info,
  236. gin::Arguments* args) {
  237. std::string url_string;
  238. args->GetNext(&url_string);
  239. [[AtomApplication sharedApplication]
  240. setCurrentActivity:base::SysUTF8ToNSString(type)
  241. withUserInfo:DictionaryValueToNSDictionary(std::move(user_info))
  242. withWebpageURL:net::NSURLWithGURL(GURL(url_string))];
  243. }
  244. std::string Browser::GetCurrentActivityType() {
  245. NSUserActivity* userActivity =
  246. [[AtomApplication sharedApplication] getCurrentActivity];
  247. return base::SysNSStringToUTF8(userActivity.activityType);
  248. }
  249. void Browser::InvalidateCurrentActivity() {
  250. [[AtomApplication sharedApplication] invalidateCurrentActivity];
  251. }
  252. void Browser::ResignCurrentActivity() {
  253. [[AtomApplication sharedApplication] resignCurrentActivity];
  254. }
  255. void Browser::UpdateCurrentActivity(const std::string& type,
  256. base::Value::Dict user_info) {
  257. [[AtomApplication sharedApplication]
  258. updateCurrentActivity:base::SysUTF8ToNSString(type)
  259. withUserInfo:DictionaryValueToNSDictionary(
  260. std::move(user_info))];
  261. }
  262. bool Browser::WillContinueUserActivity(const std::string& type) {
  263. bool prevent_default = false;
  264. for (BrowserObserver& observer : observers_)
  265. observer.OnWillContinueUserActivity(&prevent_default, type);
  266. return prevent_default;
  267. }
  268. void Browser::DidFailToContinueUserActivity(const std::string& type,
  269. const std::string& error) {
  270. for (BrowserObserver& observer : observers_)
  271. observer.OnDidFailToContinueUserActivity(type, error);
  272. }
  273. bool Browser::ContinueUserActivity(const std::string& type,
  274. base::Value::Dict user_info,
  275. base::Value::Dict details) {
  276. bool prevent_default = false;
  277. for (BrowserObserver& observer : observers_)
  278. observer.OnContinueUserActivity(&prevent_default, type, user_info.Clone(),
  279. details.Clone());
  280. return prevent_default;
  281. }
  282. void Browser::UserActivityWasContinued(const std::string& type,
  283. base::Value::Dict user_info) {
  284. for (BrowserObserver& observer : observers_)
  285. observer.OnUserActivityWasContinued(type, user_info.Clone());
  286. }
  287. bool Browser::UpdateUserActivityState(const std::string& type,
  288. base::Value::Dict user_info) {
  289. bool prevent_default = false;
  290. for (BrowserObserver& observer : observers_)
  291. observer.OnUpdateUserActivityState(&prevent_default, type,
  292. user_info.Clone());
  293. return prevent_default;
  294. }
  295. // Modified from chrome/browser/ui/cocoa/l10n_util.mm.
  296. void Browser::ApplyForcedRTL() {
  297. NSUserDefaults* defaults = NSUserDefaults.standardUserDefaults;
  298. auto dir = base::i18n::GetForcedTextDirection();
  299. // An Electron app should respect RTL behavior of application locale over
  300. // system locale.
  301. auto should_be_rtl = dir == base::i18n::RIGHT_TO_LEFT || IsAppRTL();
  302. auto should_be_ltr = dir == base::i18n::LEFT_TO_RIGHT || !IsAppRTL();
  303. // -registerDefaults: won't do the trick here because these defaults exist
  304. // (in the global domain) to reflect the system locale. They need to be set
  305. // in Chrome's domain to supersede the system value.
  306. if (should_be_rtl) {
  307. [defaults setBool:YES forKey:@"AppleTextDirection"];
  308. [defaults setBool:YES forKey:@"NSForceRightToLeftWritingDirection"];
  309. } else if (should_be_ltr) {
  310. [defaults setBool:YES forKey:@"AppleTextDirection"];
  311. [defaults setBool:NO forKey:@"NSForceRightToLeftWritingDirection"];
  312. } else {
  313. [defaults removeObjectForKey:@"AppleTextDirection"];
  314. [defaults removeObjectForKey:@"NSForceRightToLeftWritingDirection"];
  315. }
  316. }
  317. v8::Local<v8::Value> Browser::GetLoginItemSettings(
  318. const LoginItemSettings& options) {
  319. LoginItemSettings settings;
  320. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  321. if (options.type != "mainAppService" && options.service_name.empty()) {
  322. gin_helper::ErrorThrower(isolate).ThrowTypeError(
  323. "'name' is required when type is not mainAppService");
  324. return v8::Local<v8::Value>();
  325. }
  326. #if IS_MAS_BUILD()
  327. const std::string status =
  328. platform_util::GetLoginItemEnabled(options.type, options.service_name);
  329. settings.open_at_login =
  330. status == "enabled" || status == "enabled-deprecated";
  331. settings.opened_at_login = was_launched_at_login_;
  332. if (@available(macOS 13, *))
  333. settings.status = status;
  334. #else
  335. // If the app was previously set as a LoginItem with the deprecated API,
  336. // we should report its LoginItemSettings via the old API.
  337. LoginItemSettings settings_deprecated = GetLoginItemSettingsDeprecated();
  338. if (@available(macOS 13, *)) {
  339. const std::string status =
  340. platform_util::GetLoginItemEnabled(options.type, options.service_name);
  341. if (status == "enabled-deprecated") {
  342. settings = settings_deprecated;
  343. } else {
  344. settings.open_at_login = status == "enabled";
  345. settings.opened_at_login = was_launched_at_login_;
  346. settings.status = status;
  347. }
  348. } else {
  349. settings = settings_deprecated;
  350. }
  351. #endif
  352. return gin::ConvertToV8(isolate, settings);
  353. }
  354. void Browser::SetLoginItemSettings(LoginItemSettings settings) {
  355. if (settings.type != "mainAppService" && settings.service_name.empty()) {
  356. gin_helper::ErrorThrower(JavascriptEnvironment::GetIsolate())
  357. .ThrowTypeError("'name' is required when type is not mainAppService");
  358. return;
  359. }
  360. #if IS_MAS_BUILD()
  361. platform_util::SetLoginItemEnabled(settings.type, settings.service_name,
  362. settings.open_at_login);
  363. #else
  364. const base::FilePath bundle_path = base::apple::MainBundlePath();
  365. if (@available(macOS 13, *)) {
  366. // If the app was previously set as a LoginItem with the old API, remove it
  367. // as a LoginItem via the old API before re-enabling with the new API.
  368. const std::string status =
  369. platform_util::GetLoginItemEnabled("mainAppService", "");
  370. if (status == "enabled-deprecated") {
  371. base::mac::RemoveFromLoginItems(bundle_path);
  372. if (settings.open_at_login) {
  373. platform_util::SetLoginItemEnabled(settings.type, settings.service_name,
  374. settings.open_at_login);
  375. }
  376. } else {
  377. platform_util::SetLoginItemEnabled(settings.type, settings.service_name,
  378. settings.open_at_login);
  379. }
  380. } else {
  381. if (settings.open_at_login) {
  382. base::mac::AddToLoginItems(bundle_path, settings.open_as_hidden);
  383. } else {
  384. base::mac::RemoveFromLoginItems(bundle_path);
  385. }
  386. }
  387. #endif
  388. }
  389. std::string Browser::GetExecutableFileVersion() const {
  390. return GetApplicationVersion();
  391. }
  392. std::string Browser::GetExecutableFileProductName() const {
  393. return GetApplicationName();
  394. }
  395. int Browser::DockBounce(BounceType type) {
  396. return [[AtomApplication sharedApplication]
  397. requestUserAttention:static_cast<NSRequestUserAttentionType>(type)];
  398. }
  399. void Browser::DockCancelBounce(int request_id) {
  400. [[AtomApplication sharedApplication] cancelUserAttentionRequest:request_id];
  401. }
  402. void Browser::DockSetBadgeText(const std::string& label) {
  403. NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
  404. [tile setBadgeLabel:base::SysUTF8ToNSString(label)];
  405. }
  406. void Browser::DockDownloadFinished(const std::string& filePath) {
  407. [[NSDistributedNotificationCenter defaultCenter]
  408. postNotificationName:@"com.apple.DownloadFileFinished"
  409. object:base::SysUTF8ToNSString(filePath)];
  410. }
  411. std::string Browser::DockGetBadgeText() {
  412. NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
  413. return base::SysNSStringToUTF8([tile badgeLabel]);
  414. }
  415. void Browser::DockHide() {
  416. // Transforming application state from UIElement to Foreground is an
  417. // asynchronous operation, and unfortunately there is currently no way to know
  418. // when it is finished.
  419. // So if we call DockHide => DockShow => DockHide => DockShow in a very short
  420. // time, we would trigger a bug of macOS that, there would be multiple dock
  421. // icons of the app left in system.
  422. // To work around this, we make sure DockHide does nothing if it is called
  423. // immediately after DockShow. After some experiments, 1 second seems to be
  424. // a proper interval.
  425. if (!last_dock_show_.is_null() &&
  426. base::Time::Now() - last_dock_show_ < base::Seconds(1)) {
  427. return;
  428. }
  429. for (auto* const& window : WindowList::GetWindows())
  430. [window->GetNativeWindow().GetNativeNSWindow() setCanHide:NO];
  431. ProcessSerialNumber psn = {0, kCurrentProcess};
  432. TransformProcessType(&psn, kProcessTransformToUIElementApplication);
  433. }
  434. bool Browser::DockIsVisible() {
  435. // Because DockShow has a slight delay this may not be true immediately
  436. // after that call.
  437. return ([[NSRunningApplication currentApplication] activationPolicy] ==
  438. NSApplicationActivationPolicyRegular);
  439. }
  440. v8::Local<v8::Promise> Browser::DockShow(v8::Isolate* isolate) {
  441. last_dock_show_ = base::Time::Now();
  442. gin_helper::Promise<void> promise(isolate);
  443. v8::Local<v8::Promise> handle = promise.GetHandle();
  444. BOOL active = [[NSRunningApplication currentApplication] isActive];
  445. ProcessSerialNumber psn = {0, kCurrentProcess};
  446. if (active) {
  447. // Workaround buggy behavior of TransformProcessType.
  448. // http://stackoverflow.com/questions/7596643/
  449. NSArray* runningApps = [NSRunningApplication
  450. runningApplicationsWithBundleIdentifier:@"com.apple.dock"];
  451. for (NSRunningApplication* app in runningApps) {
  452. [app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  453. break;
  454. }
  455. __block gin_helper::Promise<void> p = std::move(promise);
  456. dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
  457. dispatch_after(one_ms, dispatch_get_main_queue(), ^{
  458. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  459. dispatch_time_t one_ms_2 = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
  460. dispatch_after(one_ms_2, dispatch_get_main_queue(), ^{
  461. [[NSRunningApplication currentApplication]
  462. activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  463. p.Resolve();
  464. });
  465. });
  466. } else {
  467. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  468. promise.Resolve();
  469. }
  470. return handle;
  471. }
  472. void Browser::DockSetMenu(ElectronMenuModel* model) {
  473. ElectronApplicationDelegate* delegate =
  474. (ElectronApplicationDelegate*)[NSApp delegate];
  475. [delegate setApplicationDockMenu:model];
  476. }
  477. void Browser::DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
  478. gfx::Image image;
  479. if (!icon->IsNull()) {
  480. api::NativeImage* native_image = nullptr;
  481. if (!api::NativeImage::TryConvertNativeImage(isolate, icon, &native_image))
  482. return;
  483. image = native_image->image();
  484. }
  485. // This is needed to avoid a hard CHECK when this fn is called
  486. // before the browser process is ready, since supported scales
  487. // are normally set by ui::ResourceBundle::InitSharedInstance
  488. // during browser process startup.
  489. if (!is_ready())
  490. ui::SetSupportedResourceScaleFactors({ui::k100Percent});
  491. [[AtomApplication sharedApplication]
  492. setApplicationIconImage:image.AsNSImage()];
  493. }
  494. void Browser::ShowAboutPanel() {
  495. NSDictionary* options = DictionaryValueToNSDictionary(about_panel_options_);
  496. // Credits must be a NSAttributedString instead of NSString
  497. NSString* credits = (NSString*)options[@"Credits"];
  498. if (credits != nil) {
  499. NSMutableDictionary* mutable_options = [options mutableCopy];
  500. NSAttributedString* creditString = [[NSAttributedString alloc]
  501. initWithString:credits
  502. attributes:@{NSForegroundColorAttributeName : [NSColor textColor]}];
  503. [mutable_options setValue:creditString forKey:@"Credits"];
  504. options = [NSDictionary dictionaryWithDictionary:mutable_options];
  505. }
  506. [[AtomApplication sharedApplication]
  507. orderFrontStandardAboutPanelWithOptions:options];
  508. }
  509. void Browser::SetAboutPanelOptions(base::Value::Dict options) {
  510. about_panel_options_.clear();
  511. for (const auto pair : options) {
  512. std::string key = pair.first;
  513. if (!key.empty() && pair.second.is_string()) {
  514. key[0] = base::ToUpperASCII(key[0]);
  515. about_panel_options_.Set(key, pair.second.Clone());
  516. }
  517. }
  518. }
  519. void Browser::ShowEmojiPanel() {
  520. [[AtomApplication sharedApplication] orderFrontCharacterPalette:nil];
  521. }
  522. bool Browser::IsEmojiPanelSupported() {
  523. return true;
  524. }
  525. bool Browser::IsSecureKeyboardEntryEnabled() {
  526. return password_input_enabler_.get() != nullptr;
  527. }
  528. void Browser::SetSecureKeyboardEntryEnabled(bool enabled) {
  529. if (enabled) {
  530. password_input_enabler_ =
  531. std::make_unique<ui::ScopedPasswordInputEnabler>();
  532. } else {
  533. password_input_enabler_.reset();
  534. }
  535. }
  536. } // namespace electron