browser_mac.mm 17 KB

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