browser_mac.mm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. base::DictionaryValue details) {
  232. bool prevent_default = false;
  233. for (BrowserObserver& observer : observers_)
  234. observer.OnContinueUserActivity(&prevent_default, type, user_info, details);
  235. return prevent_default;
  236. }
  237. void Browser::UserActivityWasContinued(const std::string& type,
  238. base::DictionaryValue user_info) {
  239. for (BrowserObserver& observer : observers_)
  240. observer.OnUserActivityWasContinued(type, user_info);
  241. }
  242. bool Browser::UpdateUserActivityState(const std::string& type,
  243. base::DictionaryValue user_info) {
  244. bool prevent_default = false;
  245. for (BrowserObserver& observer : observers_)
  246. observer.OnUpdateUserActivityState(&prevent_default, type, user_info);
  247. return prevent_default;
  248. }
  249. Browser::LoginItemSettings Browser::GetLoginItemSettings(
  250. const LoginItemSettings& options) {
  251. LoginItemSettings settings;
  252. #if defined(MAS_BUILD)
  253. settings.open_at_login = platform_util::GetLoginItemEnabled();
  254. #else
  255. settings.open_at_login =
  256. base::mac::CheckLoginItemStatus(&settings.open_as_hidden);
  257. settings.restore_state = base::mac::WasLaunchedAsLoginItemRestoreState();
  258. settings.opened_at_login = base::mac::WasLaunchedAsLoginOrResumeItem();
  259. settings.opened_as_hidden = base::mac::WasLaunchedAsHiddenLoginItem();
  260. #endif
  261. return settings;
  262. }
  263. // Some logic here copied from GetLoginItemForApp in base/mac/mac_util.mm
  264. void RemoveFromLoginItems() {
  265. #pragma clang diagnostic push // https://crbug.com/1154377
  266. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  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 (id login_item in login_items_array.get()) {
  277. LSSharedFileListItemRef item =
  278. reinterpret_cast<LSSharedFileListItemRef>(login_item);
  279. // kLSSharedFileListDoNotMountVolumes is used so that we don't trigger
  280. // mounting when it's not expected by a user. Just listing the login
  281. // items should not cause any side-effects.
  282. base::ScopedCFTypeRef<CFErrorRef> error;
  283. base::ScopedCFTypeRef<CFURLRef> item_url_ref(
  284. LSSharedFileListItemCopyResolvedURL(
  285. item, kLSSharedFileListDoNotMountVolumes, error.InitializeInto()));
  286. if (!error && item_url_ref) {
  287. base::ScopedCFTypeRef<CFURLRef> item_url(item_url_ref);
  288. if (CFEqual(item_url, url)) {
  289. LSSharedFileListItemRemove(login_items, item);
  290. return;
  291. }
  292. }
  293. }
  294. #pragma clang diagnostic pop
  295. }
  296. void Browser::SetLoginItemSettings(LoginItemSettings settings) {
  297. #if defined(MAS_BUILD)
  298. if (!platform_util::SetLoginItemEnabled(settings.open_at_login)) {
  299. LOG(ERROR) << "Unable to set login item enabled on sandboxed app.";
  300. }
  301. #else
  302. if (settings.open_at_login) {
  303. base::mac::AddToLoginItems(settings.open_as_hidden);
  304. } else {
  305. RemoveFromLoginItems();
  306. }
  307. #endif
  308. }
  309. std::string Browser::GetExecutableFileVersion() const {
  310. return GetApplicationVersion();
  311. }
  312. std::string Browser::GetExecutableFileProductName() const {
  313. return GetApplicationName();
  314. }
  315. int Browser::DockBounce(BounceType type) {
  316. return [[AtomApplication sharedApplication]
  317. requestUserAttention:static_cast<NSRequestUserAttentionType>(type)];
  318. }
  319. void Browser::DockCancelBounce(int request_id) {
  320. [[AtomApplication sharedApplication] cancelUserAttentionRequest:request_id];
  321. }
  322. void Browser::DockSetBadgeText(const std::string& label) {
  323. NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
  324. [tile setBadgeLabel:base::SysUTF8ToNSString(label)];
  325. }
  326. void Browser::DockDownloadFinished(const std::string& filePath) {
  327. [[NSDistributedNotificationCenter defaultCenter]
  328. postNotificationName:@"com.apple.DownloadFileFinished"
  329. object:base::SysUTF8ToNSString(filePath)];
  330. }
  331. std::string Browser::DockGetBadgeText() {
  332. NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
  333. return base::SysNSStringToUTF8([tile badgeLabel]);
  334. }
  335. void Browser::DockHide() {
  336. // Transforming application state from UIElement to Foreground is an
  337. // asyncronous operation, and unfortunately there is currently no way to know
  338. // when it is finished.
  339. // So if we call DockHide => DockShow => DockHide => DockShow in a very short
  340. // time, we would triger a bug of macOS that, there would be multiple dock
  341. // icons of the app left in system.
  342. // To work around this, we make sure DockHide does nothing if it is called
  343. // immediately after DockShow. After some experiments, 1 second seems to be
  344. // a proper interval.
  345. if (!last_dock_show_.is_null() &&
  346. base::Time::Now() - last_dock_show_ < base::Seconds(1)) {
  347. return;
  348. }
  349. for (auto* const& window : WindowList::GetWindows())
  350. [window->GetNativeWindow().GetNativeNSWindow() setCanHide:NO];
  351. ProcessSerialNumber psn = {0, kCurrentProcess};
  352. TransformProcessType(&psn, kProcessTransformToUIElementApplication);
  353. }
  354. bool Browser::DockIsVisible() {
  355. // Because DockShow has a slight delay this may not be true immediately
  356. // after that call.
  357. return ([[NSRunningApplication currentApplication] activationPolicy] ==
  358. NSApplicationActivationPolicyRegular);
  359. }
  360. v8::Local<v8::Promise> Browser::DockShow(v8::Isolate* isolate) {
  361. last_dock_show_ = base::Time::Now();
  362. gin_helper::Promise<void> promise(isolate);
  363. v8::Local<v8::Promise> handle = promise.GetHandle();
  364. BOOL active = [[NSRunningApplication currentApplication] isActive];
  365. ProcessSerialNumber psn = {0, kCurrentProcess};
  366. if (active) {
  367. // Workaround buggy behavior of TransformProcessType.
  368. // http://stackoverflow.com/questions/7596643/
  369. NSArray* runningApps = [NSRunningApplication
  370. runningApplicationsWithBundleIdentifier:@"com.apple.dock"];
  371. for (NSRunningApplication* app in runningApps) {
  372. [app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  373. break;
  374. }
  375. __block gin_helper::Promise<void> p = std::move(promise);
  376. dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
  377. dispatch_after(one_ms, dispatch_get_main_queue(), ^{
  378. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  379. dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
  380. dispatch_after(one_ms, dispatch_get_main_queue(), ^{
  381. [[NSRunningApplication currentApplication]
  382. activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  383. p.Resolve();
  384. });
  385. });
  386. } else {
  387. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  388. promise.Resolve();
  389. }
  390. return handle;
  391. }
  392. void Browser::DockSetMenu(ElectronMenuModel* model) {
  393. ElectronApplicationDelegate* delegate =
  394. (ElectronApplicationDelegate*)[NSApp delegate];
  395. [delegate setApplicationDockMenu:model];
  396. }
  397. void Browser::DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
  398. gfx::Image image;
  399. if (!icon->IsNull()) {
  400. api::NativeImage* native_image = nullptr;
  401. if (!api::NativeImage::TryConvertNativeImage(isolate, icon, &native_image))
  402. return;
  403. image = native_image->image();
  404. }
  405. [[AtomApplication sharedApplication]
  406. setApplicationIconImage:image.AsNSImage()];
  407. }
  408. void Browser::ShowAboutPanel() {
  409. NSDictionary* options = DictionaryValueToNSDictionary(about_panel_options_);
  410. // Credits must be a NSAttributedString instead of NSString
  411. NSString* credits = (NSString*)options[@"Credits"];
  412. if (credits != nil) {
  413. base::scoped_nsobject<NSMutableDictionary> mutable_options(
  414. [options mutableCopy]);
  415. base::scoped_nsobject<NSAttributedString> creditString(
  416. [[NSAttributedString alloc]
  417. initWithString:credits
  418. attributes:@{
  419. NSForegroundColorAttributeName : [NSColor textColor]
  420. }]);
  421. [mutable_options setValue:creditString forKey:@"Credits"];
  422. options = [NSDictionary dictionaryWithDictionary:mutable_options];
  423. }
  424. [[AtomApplication sharedApplication]
  425. orderFrontStandardAboutPanelWithOptions:options];
  426. }
  427. void Browser::SetAboutPanelOptions(base::DictionaryValue options) {
  428. about_panel_options_.DictClear();
  429. for (const auto pair : options.DictItems()) {
  430. std::string key = std::string(pair.first);
  431. if (!key.empty() && pair.second.is_string()) {
  432. key[0] = base::ToUpperASCII(key[0]);
  433. auto val = std::make_unique<base::Value>(pair.second.Clone());
  434. about_panel_options_.Set(key, std::move(val));
  435. }
  436. }
  437. }
  438. void Browser::ShowEmojiPanel() {
  439. [[AtomApplication sharedApplication] orderFrontCharacterPalette:nil];
  440. }
  441. bool Browser::IsEmojiPanelSupported() {
  442. return true;
  443. }
  444. bool Browser::IsSecureKeyboardEntryEnabled() {
  445. return password_input_enabler_.get() != nullptr;
  446. }
  447. void Browser::SetSecureKeyboardEntryEnabled(bool enabled) {
  448. if (enabled) {
  449. password_input_enabler_ =
  450. std::make_unique<ui::ScopedPasswordInputEnabler>();
  451. } else {
  452. password_input_enabler_.reset();
  453. }
  454. }
  455. } // namespace electron