browser_mac.mm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. base::string16 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. base::string16 app_path = base::SysNSStringToUTF16(ns_app_path);
  70. base::string16 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::Callback<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. base::string16 Browser::GetApplicationNameForProtocol(const GURL& url) {
  173. NSString* app_path = GetAppPathForProtocol(url);
  174. if (!app_path) {
  175. return base::string16();
  176. }
  177. base::string16 app_display_name = GetAppDisplayNameForProtocol(app_path);
  178. return app_display_name;
  179. }
  180. void Browser::SetAppUserModelID(const base::string16& name) {}
  181. bool Browser::SetBadgeCount(base::Optional<int> count) {
  182. DockSetBadgeText(!count.has_value() || count.value() != 0
  183. ? badging::BadgeManager::GetBadgeString(count)
  184. : "");
  185. if (count.has_value()) {
  186. badge_count_ = count.value();
  187. } else {
  188. badge_count_ = 0;
  189. }
  190. return true;
  191. }
  192. void Browser::SetUserActivity(const std::string& type,
  193. base::DictionaryValue user_info,
  194. gin::Arguments* args) {
  195. std::string url_string;
  196. args->GetNext(&url_string);
  197. [[AtomApplication sharedApplication]
  198. setCurrentActivity:base::SysUTF8ToNSString(type)
  199. withUserInfo:DictionaryValueToNSDictionary(user_info)
  200. withWebpageURL:net::NSURLWithGURL(GURL(url_string))];
  201. }
  202. std::string Browser::GetCurrentActivityType() {
  203. NSUserActivity* userActivity =
  204. [[AtomApplication sharedApplication] getCurrentActivity];
  205. return base::SysNSStringToUTF8(userActivity.activityType);
  206. }
  207. void Browser::InvalidateCurrentActivity() {
  208. [[AtomApplication sharedApplication] invalidateCurrentActivity];
  209. }
  210. void Browser::ResignCurrentActivity() {
  211. [[AtomApplication sharedApplication] resignCurrentActivity];
  212. }
  213. void Browser::UpdateCurrentActivity(const std::string& type,
  214. base::DictionaryValue user_info) {
  215. [[AtomApplication sharedApplication]
  216. updateCurrentActivity:base::SysUTF8ToNSString(type)
  217. withUserInfo:DictionaryValueToNSDictionary(user_info)];
  218. }
  219. bool Browser::WillContinueUserActivity(const std::string& type) {
  220. bool prevent_default = false;
  221. for (BrowserObserver& observer : observers_)
  222. observer.OnWillContinueUserActivity(&prevent_default, type);
  223. return prevent_default;
  224. }
  225. void Browser::DidFailToContinueUserActivity(const std::string& type,
  226. const std::string& error) {
  227. for (BrowserObserver& observer : observers_)
  228. observer.OnDidFailToContinueUserActivity(type, error);
  229. }
  230. bool Browser::ContinueUserActivity(const std::string& type,
  231. base::DictionaryValue user_info) {
  232. bool prevent_default = false;
  233. for (BrowserObserver& observer : observers_)
  234. observer.OnContinueUserActivity(&prevent_default, type, user_info);
  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. void RemoveFromLoginItems() {
  264. #pragma clang diagnostic push // https://crbug.com/1154377
  265. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  266. // logic to find the login item copied from GetLoginItemForApp in
  267. // base/mac/mac_util.mm
  268. base::ScopedCFTypeRef<LSSharedFileListRef> login_items(
  269. LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL));
  270. if (!login_items.get()) {
  271. LOG(ERROR) << "Couldn't get a Login Items list.";
  272. return;
  273. }
  274. base::scoped_nsobject<NSArray> login_items_array(
  275. base::mac::CFToNSCast(LSSharedFileListCopySnapshot(login_items, NULL)));
  276. NSURL* url = [NSURL fileURLWithPath:[base::mac::MainBundle() bundlePath]];
  277. for (NSUInteger i = 0; i < [login_items_array count]; ++i) {
  278. LSSharedFileListItemRef item =
  279. reinterpret_cast<LSSharedFileListItemRef>(login_items_array[i]);
  280. base::ScopedCFTypeRef<CFErrorRef> error;
  281. CFURLRef item_url_ref =
  282. LSSharedFileListItemCopyResolvedURL(item, 0, error.InitializeInto());
  283. if (!error && item_url_ref) {
  284. base::ScopedCFTypeRef<CFURLRef> item_url(item_url_ref);
  285. if (CFEqual(item_url, url)) {
  286. LSSharedFileListItemRemove(login_items, item);
  287. return;
  288. }
  289. }
  290. }
  291. #pragma clang diagnostic pop
  292. }
  293. void Browser::SetLoginItemSettings(LoginItemSettings settings) {
  294. #if defined(MAS_BUILD)
  295. if (!platform_util::SetLoginItemEnabled(settings.open_at_login)) {
  296. LOG(ERROR) << "Unable to set login item enabled on sandboxed app.";
  297. }
  298. #else
  299. if (settings.open_at_login) {
  300. base::mac::AddToLoginItems(settings.open_as_hidden);
  301. } else {
  302. RemoveFromLoginItems();
  303. }
  304. #endif
  305. }
  306. std::string Browser::GetExecutableFileVersion() const {
  307. return GetApplicationVersion();
  308. }
  309. std::string Browser::GetExecutableFileProductName() const {
  310. return GetApplicationName();
  311. }
  312. int Browser::DockBounce(BounceType type) {
  313. return [[AtomApplication sharedApplication]
  314. requestUserAttention:static_cast<NSRequestUserAttentionType>(type)];
  315. }
  316. void Browser::DockCancelBounce(int request_id) {
  317. [[AtomApplication sharedApplication] cancelUserAttentionRequest:request_id];
  318. }
  319. void Browser::DockSetBadgeText(const std::string& label) {
  320. NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
  321. [tile setBadgeLabel:base::SysUTF8ToNSString(label)];
  322. }
  323. void Browser::DockDownloadFinished(const std::string& filePath) {
  324. [[NSDistributedNotificationCenter defaultCenter]
  325. postNotificationName:@"com.apple.DownloadFileFinished"
  326. object:base::SysUTF8ToNSString(filePath)];
  327. }
  328. std::string Browser::DockGetBadgeText() {
  329. NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
  330. return base::SysNSStringToUTF8([tile badgeLabel]);
  331. }
  332. void Browser::DockHide() {
  333. // Transforming application state from UIElement to Foreground is an
  334. // asyncronous operation, and unfortunately there is currently no way to know
  335. // when it is finished.
  336. // So if we call DockHide => DockShow => DockHide => DockShow in a very short
  337. // time, we would triger a bug of macOS that, there would be multiple dock
  338. // icons of the app left in system.
  339. // To work around this, we make sure DockHide does nothing if it is called
  340. // immediately after DockShow. After some experiments, 1 second seems to be
  341. // a proper interval.
  342. if (!last_dock_show_.is_null() &&
  343. base::Time::Now() - last_dock_show_ < base::TimeDelta::FromSeconds(1)) {
  344. return;
  345. }
  346. for (auto* const& window : WindowList::GetWindows())
  347. [window->GetNativeWindow().GetNativeNSWindow() setCanHide:NO];
  348. ProcessSerialNumber psn = {0, kCurrentProcess};
  349. TransformProcessType(&psn, kProcessTransformToUIElementApplication);
  350. }
  351. bool Browser::DockIsVisible() {
  352. // Because DockShow has a slight delay this may not be true immediately
  353. // after that call.
  354. return ([[NSRunningApplication currentApplication] activationPolicy] ==
  355. NSApplicationActivationPolicyRegular);
  356. }
  357. v8::Local<v8::Promise> Browser::DockShow(v8::Isolate* isolate) {
  358. last_dock_show_ = base::Time::Now();
  359. gin_helper::Promise<void> promise(isolate);
  360. v8::Local<v8::Promise> handle = promise.GetHandle();
  361. BOOL active = [[NSRunningApplication currentApplication] isActive];
  362. ProcessSerialNumber psn = {0, kCurrentProcess};
  363. if (active) {
  364. // Workaround buggy behavior of TransformProcessType.
  365. // http://stackoverflow.com/questions/7596643/
  366. NSArray* runningApps = [NSRunningApplication
  367. runningApplicationsWithBundleIdentifier:@"com.apple.dock"];
  368. for (NSRunningApplication* app in runningApps) {
  369. [app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  370. break;
  371. }
  372. __block gin_helper::Promise<void> p = std::move(promise);
  373. dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
  374. dispatch_after(one_ms, dispatch_get_main_queue(), ^{
  375. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  376. dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
  377. dispatch_after(one_ms, dispatch_get_main_queue(), ^{
  378. [[NSRunningApplication currentApplication]
  379. activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  380. p.Resolve();
  381. });
  382. });
  383. } else {
  384. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  385. promise.Resolve();
  386. }
  387. return handle;
  388. }
  389. void Browser::DockSetMenu(ElectronMenuModel* model) {
  390. ElectronApplicationDelegate* delegate =
  391. (ElectronApplicationDelegate*)[NSApp delegate];
  392. [delegate setApplicationDockMenu:model];
  393. }
  394. void Browser::DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
  395. gfx::Image image;
  396. if (!icon->IsNull()) {
  397. api::NativeImage* native_image = nullptr;
  398. if (!api::NativeImage::TryConvertNativeImage(isolate, icon, &native_image))
  399. return;
  400. image = native_image->image();
  401. }
  402. [[AtomApplication sharedApplication]
  403. setApplicationIconImage:image.AsNSImage()];
  404. }
  405. void Browser::ShowAboutPanel() {
  406. NSDictionary* options = DictionaryValueToNSDictionary(about_panel_options_);
  407. // Credits must be a NSAttributedString instead of NSString
  408. NSString* credits = (NSString*)options[@"Credits"];
  409. if (credits != nil) {
  410. base::scoped_nsobject<NSMutableDictionary> mutable_options(
  411. [options mutableCopy]);
  412. base::scoped_nsobject<NSAttributedString> creditString(
  413. [[NSAttributedString alloc]
  414. initWithString:credits
  415. attributes:@{
  416. NSForegroundColorAttributeName : [NSColor textColor]
  417. }]);
  418. [mutable_options setValue:creditString forKey:@"Credits"];
  419. options = [NSDictionary dictionaryWithDictionary:mutable_options];
  420. }
  421. [[AtomApplication sharedApplication]
  422. orderFrontStandardAboutPanelWithOptions:options];
  423. }
  424. void Browser::SetAboutPanelOptions(base::DictionaryValue options) {
  425. about_panel_options_.Clear();
  426. for (auto& pair : options) {
  427. std::string& key = pair.first;
  428. if (!key.empty() && pair.second->is_string()) {
  429. key[0] = base::ToUpperASCII(key[0]);
  430. about_panel_options_.Set(key, std::move(pair.second));
  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