atom_api_menu_mac.mm 6.4 KB

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