menu_gtk.cc 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "shell/browser/ui/gtk/menu_gtk.h"
  5. #include <gtk/gtk.h>
  6. #include "base/functional/bind.h"
  7. #include "shell/browser/ui/gtk/menu_util.h"
  8. #include "ui/base/models/menu_model.h"
  9. namespace electron::gtkui {
  10. MenuGtk::MenuGtk(ui::MenuModel* model)
  11. : menu_model_(model), gtk_menu_(TakeGObject(gtk_menu_new())) {
  12. if (menu_model_) {
  13. BuildSubmenuFromModel(menu_model_, gtk_menu_,
  14. base::BindRepeating(&MenuGtk::OnMenuItemActivated,
  15. base::Unretained(this)),
  16. &block_activation_, &signals_);
  17. Refresh();
  18. }
  19. }
  20. MenuGtk::~MenuGtk() {
  21. gtk_widget_destroy(gtk_menu_);
  22. }
  23. void MenuGtk::Refresh() {
  24. gtk_container_foreach(GTK_CONTAINER(gtk_menu_.get()), SetMenuItemInfo,
  25. &block_activation_);
  26. }
  27. GtkMenu* MenuGtk::GetGtkMenu() {
  28. return GTK_MENU(gtk_menu_.get());
  29. }
  30. void MenuGtk::OnMenuItemActivated(GtkWidget* menu_item) {
  31. if (block_activation_)
  32. return;
  33. ui::MenuModel* model = ModelForMenuItem(GTK_MENU_ITEM(menu_item));
  34. if (!model) {
  35. // There won't be a model for "native" submenus like the "Input Methods"
  36. // context menu. We don't need to handle activation messages for submenus
  37. // anyway, so we can just return here.
  38. DCHECK(gtk_menu_item_get_submenu(GTK_MENU_ITEM(menu_item)));
  39. return;
  40. }
  41. // The activate signal is sent to radio items as they get deselected;
  42. // ignore it in this case.
  43. if (GTK_IS_RADIO_MENU_ITEM(menu_item) &&
  44. !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menu_item))) {
  45. return;
  46. }
  47. int id;
  48. if (!GetMenuItemID(menu_item, &id))
  49. return;
  50. // The menu item can still be activated by hotkeys even if it is disabled.
  51. if (model->IsEnabledAt(id))
  52. ExecuteCommand(model, id);
  53. }
  54. } // namespace electron::gtkui