atom_api_menu_mac.mm 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. #import "shell/browser/api/atom_api_menu_mac.h"
  5. #include <string>
  6. #include <utility>
  7. #include "base/mac/scoped_sending_event.h"
  8. #include "base/message_loop/message_loop_current.h"
  9. #include "base/strings/sys_string_conversions.h"
  10. #include "base/task/post_task.h"
  11. #include "content/public/browser/browser_task_traits.h"
  12. #include "content/public/browser/browser_thread.h"
  13. #include "content/public/browser/web_contents.h"
  14. #include "shell/browser/native_window.h"
  15. #include "shell/browser/unresponsive_suppressor.h"
  16. #include "shell/common/node_includes.h"
  17. using content::BrowserThread;
  18. namespace {
  19. static scoped_nsobject<NSMenu> applicationMenu_;
  20. } // namespace
  21. namespace electron {
  22. namespace api {
  23. MenuMac::MenuMac(v8::Isolate* isolate, v8::Local<v8::Object> wrapper)
  24. : Menu(isolate, wrapper), weak_factory_(this) {}
  25. MenuMac::~MenuMac() = default;
  26. void MenuMac::PopupAt(TopLevelWindow* window,
  27. int x,
  28. int y,
  29. int positioning_item,
  30. base::OnceClosure callback) {
  31. NativeWindow* native_window = window->window();
  32. if (!native_window)
  33. return;
  34. // Make sure the Menu object would not be garbage-collected until the callback
  35. // has run.
  36. base::OnceClosure callback_with_ref = BindSelfToClosure(std::move(callback));
  37. auto popup =
  38. base::BindOnce(&MenuMac::PopupOnUI, weak_factory_.GetWeakPtr(),
  39. native_window->GetWeakPtr(), window->weak_map_id(), x, y,
  40. positioning_item, std::move(callback_with_ref));
  41. base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, std::move(popup));
  42. }
  43. void MenuMac::PopupOnUI(const base::WeakPtr<NativeWindow>& native_window,
  44. int32_t window_id,
  45. int x,
  46. int y,
  47. int positioning_item,
  48. base::OnceClosure callback) {
  49. if (!native_window)
  50. return;
  51. NSWindow* nswindow = native_window->GetNativeWindow().GetNativeNSWindow();
  52. base::OnceClosure close_callback =
  53. base::BindOnce(&MenuMac::OnClosed, weak_factory_.GetWeakPtr(), window_id,
  54. std::move(callback));
  55. popup_controllers_[window_id] = base::scoped_nsobject<AtomMenuController>(
  56. [[AtomMenuController alloc] initWithModel:model()
  57. useDefaultAccelerator:NO]);
  58. NSMenu* menu = [popup_controllers_[window_id] menu];
  59. NSView* view = [nswindow contentView];
  60. // Which menu item to show.
  61. NSMenuItem* item = nil;
  62. if (positioning_item < [menu numberOfItems] && positioning_item >= 0)
  63. item = [menu itemAtIndex:positioning_item];
  64. // (-1, -1) means showing on mouse location.
  65. NSPoint position;
  66. if (x == -1 || y == -1) {
  67. position = [view convertPoint:[nswindow mouseLocationOutsideOfEventStream]
  68. fromView:nil];
  69. } else {
  70. position = NSMakePoint(x, [view frame].size.height - y);
  71. }
  72. // If no preferred item is specified, try to show all of the menu items.
  73. if (!positioning_item) {
  74. CGFloat windowBottom = CGRectGetMinY([view window].frame);
  75. CGFloat lowestMenuPoint = windowBottom + position.y - [menu size].height;
  76. CGFloat screenBottom = CGRectGetMinY([view window].screen.frame);
  77. CGFloat distanceFromBottom = lowestMenuPoint - screenBottom;
  78. if (distanceFromBottom < 0)
  79. position.y = position.y - distanceFromBottom + 4;
  80. }
  81. // Place the menu left of cursor if it is overflowing off right of screen.
  82. CGFloat windowLeft = CGRectGetMinX([view window].frame);
  83. CGFloat rightmostMenuPoint = windowLeft + position.x + [menu size].width;
  84. CGFloat screenRight = CGRectGetMaxX([view window].screen.frame);
  85. if (rightmostMenuPoint > screenRight)
  86. position.x = position.x - [menu size].width;
  87. [popup_controllers_[window_id] setCloseCallback:std::move(close_callback)];
  88. // Make sure events can be pumped while the menu is up.
  89. base::MessageLoopCurrent::ScopedNestableTaskAllower allow;
  90. // One of the events that could be pumped is |window.close()|.
  91. // User-initiated event-tracking loops protect against this by
  92. // setting flags in -[CrApplication sendEvent:], but since
  93. // web-content menus are initiated by IPC message the setup has to
  94. // be done manually.
  95. base::mac::ScopedSendingEvent sendingEventScoper;
  96. // Don't emit unresponsive event when showing menu.
  97. electron::UnresponsiveSuppressor suppressor;
  98. [menu popUpMenuPositioningItem:item atLocation:position inView:view];
  99. }
  100. void MenuMac::ClosePopupAt(int32_t window_id) {
  101. auto controller = popup_controllers_.find(window_id);
  102. if (controller != popup_controllers_.end()) {
  103. // Close the controller for the window.
  104. [controller->second cancel];
  105. } else if (window_id == -1) {
  106. // Or just close all opened controllers.
  107. for (auto it = popup_controllers_.begin();
  108. it != popup_controllers_.end();) {
  109. // The iterator is invalidated after the call.
  110. [(it++)->second cancel];
  111. }
  112. }
  113. }
  114. void MenuMac::OnClosed(int32_t window_id, base::OnceClosure callback) {
  115. popup_controllers_.erase(window_id);
  116. std::move(callback).Run();
  117. }
  118. // static
  119. void Menu::SetApplicationMenu(Menu* base_menu) {
  120. MenuMac* menu = static_cast<MenuMac*>(base_menu);
  121. base::scoped_nsobject<AtomMenuController> menu_controller(
  122. [[AtomMenuController alloc] initWithModel:menu->model_.get()
  123. useDefaultAccelerator:YES]);
  124. NSRunLoop* currentRunLoop = [NSRunLoop currentRunLoop];
  125. [currentRunLoop cancelPerformSelector:@selector(setMainMenu:)
  126. target:NSApp
  127. argument:applicationMenu_];
  128. applicationMenu_.reset([[menu_controller menu] retain]);
  129. [[NSRunLoop currentRunLoop]
  130. performSelector:@selector(setMainMenu:)
  131. target:NSApp
  132. argument:applicationMenu_
  133. order:0
  134. modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
  135. // Ensure the menu_controller_ is destroyed after main menu is set.
  136. menu_controller.swap(menu->menu_controller_);
  137. }
  138. // static
  139. void Menu::SendActionToFirstResponder(const std::string& action) {
  140. SEL selector = NSSelectorFromString(base::SysUTF8ToNSString(action));
  141. [NSApp sendAction:selector to:nil from:[NSApp mainMenu]];
  142. }
  143. // static
  144. mate::WrappableBase* Menu::New(mate::Arguments* args) {
  145. return new MenuMac(args->isolate(), args->GetThis());
  146. }
  147. } // namespace api
  148. } // namespace electron