browser_mac.mm 22 KB

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