• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 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 
5 #include "libcef/browser/native/native_menu_win.h"
6 
7 #include "libcef/browser/native/menu_2.h"
8 
9 #include "base/bind.h"
10 #include "base/logging.h"
11 #include "base/memory/ptr_util.h"
12 #include "base/stl_util.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/threading/thread_task_runner_handle.h"
16 #include "base/win/wrapped_window_proc.h"
17 #include "skia/ext/platform_canvas.h"
18 #include "skia/ext/skia_utils_win.h"
19 #include "ui/base/accelerators/accelerator.h"
20 #include "ui/base/l10n/l10n_util.h"
21 #include "ui/base/l10n/l10n_util_win.h"
22 #include "ui/base/models/image_model.h"
23 #include "ui/base/models/menu_model.h"
24 #include "ui/events/keycodes/keyboard_codes.h"
25 #include "ui/gfx/canvas.h"
26 #include "ui/gfx/font_list.h"
27 #include "ui/gfx/geometry/rect.h"
28 #include "ui/gfx/image/image.h"
29 #include "ui/gfx/image/image_skia.h"
30 #include "ui/gfx/text_utils.h"
31 #include "ui/gfx/win/hwnd_util.h"
32 #include "ui/native_theme/native_theme.h"
33 #include "ui/native_theme/themed_vector_icon.h"
34 #include "ui/views/controls/menu/menu_config.h"
35 #include "ui/views/controls/menu/menu_insertion_delegate_win.h"
36 
37 using ui::NativeTheme;
38 
39 namespace views {
40 
41 // The width of an icon, including the pixels between the icon and
42 // the item label.
43 static const int kIconWidth = 23;
44 // Margins between the top of the item and the label.
45 static const int kItemTopMargin = 3;
46 // Margins between the bottom of the item and the label.
47 static const int kItemBottomMargin = 4;
48 // Margins between the left of the item and the icon.
49 static const int kItemLeftMargin = 4;
50 // The width for displaying the sub-menu arrow.
51 static const int kArrowWidth = 10;
52 
53 // Horizontal spacing between the end of an item (i.e. an icon or a checkbox)
54 // and the start of its corresponding text.
55 constexpr int kItemLabelSpacing = 10;
56 
57 namespace {
58 
59 // Draws the top layer of the canvas into the specified HDC. Only works
60 // with a SkCanvas with a BitmapPlatformDevice. Will create a temporary
61 // HDC to back the canvas if one doesn't already exist, tearing it down
62 // before returning. If |src_rect| is null, copies the entire canvas.
63 // Deleted from skia/ext/platform_canvas.h in https://crbug.com/675977#c13
DrawToNativeContext(SkCanvas * canvas,HDC destination_hdc,int x,int y,const RECT * src_rect)64 void DrawToNativeContext(SkCanvas* canvas,
65                          HDC destination_hdc,
66                          int x,
67                          int y,
68                          const RECT* src_rect) {
69   RECT temp_rect;
70   if (!src_rect) {
71     temp_rect.left = 0;
72     temp_rect.right = canvas->imageInfo().width();
73     temp_rect.top = 0;
74     temp_rect.bottom = canvas->imageInfo().height();
75     src_rect = &temp_rect;
76   }
77   skia::CopyHDC(skia::GetNativeDrawingContext(canvas), destination_hdc, x, y,
78                 canvas->imageInfo().isOpaque(), *src_rect,
79                 canvas->getTotalMatrix());
80 }
81 
CreateNativeFont(const gfx::Font & font)82 HFONT CreateNativeFont(const gfx::Font& font) {
83   // Extracts |fonts| properties.
84   const DWORD italic = (font.GetStyle() & gfx::Font::ITALIC) ? TRUE : FALSE;
85   const DWORD underline =
86       (font.GetStyle() & gfx::Font::UNDERLINE) ? TRUE : FALSE;
87   // The font mapper matches its absolute value against the character height of
88   // the available fonts.
89   const int height = -font.GetFontSize();
90 
91   // Select the primary font which forces a mapping to a physical font.
92   return ::CreateFont(height, 0, 0, 0, static_cast<int>(font.GetWeight()),
93                       italic, underline, FALSE, DEFAULT_CHARSET,
94                       OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
95                       DEFAULT_PITCH | FF_DONTCARE,
96                       base::UTF8ToWide(font.GetFontName()).c_str());
97 }
98 
99 }  // namespace
100 
101 struct CefNativeMenuWin::ItemData {
102   // The Windows API requires that whoever creates the menus must own the
103   // strings used for labels, and keep them around for the lifetime of the
104   // created menu. So be it.
105   std::wstring label;
106 
107   // Someone needs to own submenus, it may as well be us.
108   std::unique_ptr<Menu2> submenu;
109 
110   // We need a pointer back to the containing menu in various circumstances.
111   CefNativeMenuWin* native_menu_win;
112 
113   // The index of the item within the menu's model.
114   int model_index;
115 };
116 
117 // Returns the CefNativeMenuWin for a particular HMENU.
GetCefNativeMenuWinFromHMENU(HMENU hmenu)118 static CefNativeMenuWin* GetCefNativeMenuWinFromHMENU(HMENU hmenu) {
119   MENUINFO mi = {0};
120   mi.cbSize = sizeof(mi);
121   mi.fMask = MIM_MENUDATA | MIM_STYLE;
122   GetMenuInfo(hmenu, &mi);
123   return reinterpret_cast<CefNativeMenuWin*>(mi.dwMenuData);
124 }
125 
126 // A window that receives messages from Windows relevant to the native menu
127 // structure we have constructed in CefNativeMenuWin.
128 class CefNativeMenuWin::MenuHostWindow {
129  public:
MenuHostWindow()130   MenuHostWindow() {
131     RegisterClass();
132     hwnd_ = CreateWindowEx(l10n_util::GetExtendedStyles(), kWindowClassName,
133                            L"", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL);
134     gfx::CheckWindowCreated(hwnd_, ::GetLastError());
135     gfx::SetWindowUserData(hwnd_, this);
136   }
137 
~MenuHostWindow()138   ~MenuHostWindow() { DestroyWindow(hwnd_); }
139 
hwnd() const140   HWND hwnd() const { return hwnd_; }
141 
142  private:
143   static const wchar_t* kWindowClassName;
144 
RegisterClass()145   void RegisterClass() {
146     static bool registered = false;
147     if (registered)
148       return;
149 
150     WNDCLASSEX window_class;
151     base::win::InitializeWindowClass(
152         kWindowClassName, &base::win::WrappedWindowProc<MenuHostWindowProc>,
153         CS_DBLCLKS, 0, 0, NULL, reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1),
154         NULL, NULL, NULL, &window_class);
155     ATOM clazz = RegisterClassEx(&window_class);
156     CHECK(clazz);
157     registered = true;
158   }
159 
160   // Converts the WPARAM value passed to WM_MENUSELECT into an index
161   // corresponding to the menu item that was selected.
GetMenuItemIndexFromWPARAM(HMENU menu,WPARAM w_param) const162   int GetMenuItemIndexFromWPARAM(HMENU menu, WPARAM w_param) const {
163     int count = GetMenuItemCount(menu);
164     // For normal command menu items, Windows passes a command id as the LOWORD
165     // of WPARAM for WM_MENUSELECT. We need to walk forward through the menu
166     // items to find an item with a matching ID. Ugh!
167     for (int i = 0; i < count; ++i) {
168       MENUITEMINFO mii = {0};
169       mii.cbSize = sizeof(mii);
170       mii.fMask = MIIM_ID;
171       GetMenuItemInfo(menu, i, MF_BYPOSITION, &mii);
172       if (mii.wID == w_param)
173         return i;
174     }
175     // If we didn't find a matching command ID, this means a submenu has been
176     // selected instead, and rather than passing a command ID in
177     // LOWORD(w_param), Windows has actually passed us a position, so we just
178     // return it.
179     return w_param;
180   }
181 
GetItemData(ULONG_PTR item_data)182   CefNativeMenuWin::ItemData* GetItemData(ULONG_PTR item_data) {
183     return reinterpret_cast<CefNativeMenuWin::ItemData*>(item_data);
184   }
185 
186   // Called when the user selects a specific item.
OnMenuCommand(int position,HMENU menu)187   void OnMenuCommand(int position, HMENU menu) {
188     CefNativeMenuWin* menu_win = GetCefNativeMenuWinFromHMENU(menu);
189     ui::MenuModel* model = menu_win->model_;
190     CefNativeMenuWin* root_menu = menu_win;
191     while (root_menu->parent_)
192       root_menu = root_menu->parent_;
193 
194     // Only notify the model if it didn't already send out notification.
195     // See comment in MenuMessageHook for details.
196     if (root_menu->menu_action_ == MenuWrapper::MENU_ACTION_NONE)
197       model->ActivatedAt(position);
198   }
199 
200   // Called by Windows to measure the size of an owner-drawn menu item.
OnMeasureItem(WPARAM w_param,MEASUREITEMSTRUCT * measure_item_struct)201   void OnMeasureItem(WPARAM w_param, MEASUREITEMSTRUCT* measure_item_struct) {
202     CefNativeMenuWin::ItemData* data =
203         GetItemData(measure_item_struct->itemData);
204     if (data) {
205       gfx::FontList font_list;
206       measure_item_struct->itemWidth =
207           gfx::GetStringWidth(base::WideToUTF16(data->label), font_list) +
208           kIconWidth + kItemLeftMargin + kItemLabelSpacing -
209           GetSystemMetrics(SM_CXMENUCHECK);
210       if (data->submenu.get())
211         measure_item_struct->itemWidth += kArrowWidth;
212       // If the label contains an accelerator, make room for tab.
213       if (data->label.find(L'\t') != std::wstring::npos)
214         measure_item_struct->itemWidth += gfx::GetStringWidth(u" ", font_list);
215       measure_item_struct->itemHeight =
216           font_list.GetHeight() + kItemBottomMargin + kItemTopMargin;
217     } else {
218       // Measure separator size.
219       measure_item_struct->itemHeight = GetSystemMetrics(SM_CYMENU) / 2;
220       measure_item_struct->itemWidth = 0;
221     }
222   }
223 
224   // Called by Windows to paint an owner-drawn menu item.
OnDrawItem(UINT w_param,DRAWITEMSTRUCT * draw_item_struct)225   void OnDrawItem(UINT w_param, DRAWITEMSTRUCT* draw_item_struct) {
226     HDC dc = draw_item_struct->hDC;
227     COLORREF prev_bg_color, prev_text_color;
228 
229     // Set background color and text color
230     if (draw_item_struct->itemState & ODS_SELECTED) {
231       prev_bg_color = SetBkColor(dc, GetSysColor(COLOR_HIGHLIGHT));
232       prev_text_color = SetTextColor(dc, GetSysColor(COLOR_HIGHLIGHTTEXT));
233     } else {
234       prev_bg_color = SetBkColor(dc, GetSysColor(COLOR_MENU));
235       if (draw_item_struct->itemState & ODS_DISABLED)
236         prev_text_color = SetTextColor(dc, GetSysColor(COLOR_GRAYTEXT));
237       else
238         prev_text_color = SetTextColor(dc, GetSysColor(COLOR_MENUTEXT));
239     }
240 
241     if (draw_item_struct->itemData) {
242       CefNativeMenuWin::ItemData* data =
243           GetItemData(draw_item_struct->itemData);
244       // Draw the background.
245       HBRUSH hbr = CreateSolidBrush(GetBkColor(dc));
246       FillRect(dc, &draw_item_struct->rcItem, hbr);
247       DeleteObject(hbr);
248 
249       // Draw the label.
250       RECT rect = draw_item_struct->rcItem;
251       rect.top += kItemTopMargin;
252       // Should we add kIconWidth only when icon.width() != 0 ?
253       rect.left += kItemLeftMargin + kIconWidth;
254       rect.right -= kItemLabelSpacing;
255       UINT format = DT_TOP | DT_SINGLELINE;
256       // Check whether the mnemonics should be underlined.
257       BOOL underline_mnemonics;
258       SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &underline_mnemonics, 0);
259       if (!underline_mnemonics)
260         format |= DT_HIDEPREFIX;
261       gfx::FontList font_list;
262       HFONT new_font = CreateNativeFont(font_list.GetPrimaryFont());
263       HGDIOBJ old_font = SelectObject(dc, new_font);
264 
265       // If an accelerator is specified (with a tab delimiting the rest of the
266       // label from the accelerator), we have to justify the fist part on the
267       // left and the accelerator on the right.
268       // TODO(jungshik): This will break in RTL UI. Currently, he/ar use the
269       //                 window system UI font and will not hit here.
270       std::wstring label = data->label;
271       std::wstring accel;
272       std::wstring::size_type tab_pos = label.find(L'\t');
273       if (tab_pos != std::wstring::npos) {
274         accel = label.substr(tab_pos);
275         label = label.substr(0, tab_pos);
276       }
277       DrawTextEx(dc, const_cast<wchar_t*>(label.data()),
278                  static_cast<int>(label.size()), &rect, format | DT_LEFT, NULL);
279       if (!accel.empty()) {
280         DrawTextEx(dc, const_cast<wchar_t*>(accel.data()),
281                    static_cast<int>(accel.size()), &rect, format | DT_RIGHT,
282                    NULL);
283       }
284       SelectObject(dc, old_font);
285       DeleteObject(new_font);
286 
287       ui::MenuModel::ItemType type =
288           data->native_menu_win->model_->GetTypeAt(data->model_index);
289 
290       // Draw the icon after the label, otherwise it would be covered
291       // by the label.
292       ui::ImageModel icon =
293           data->native_menu_win->model_->GetIconAt(data->model_index);
294       if (icon.IsImage() || icon.IsVectorIcon()) {
295         ui::NativeTheme* native_theme =
296             ui::NativeTheme::GetInstanceForNativeUi();
297 
298         // We currently don't support items with both icons and checkboxes.
299         const gfx::ImageSkia skia_icon =
300             icon.IsImage() ? icon.GetImage().AsImageSkia()
301                            : ui::ThemedVectorIcon(icon.GetVectorIcon())
302                                  .GetImageSkia(native_theme, 16);
303 
304         DCHECK(type != ui::MenuModel::TYPE_CHECK);
305         std::unique_ptr<SkCanvas> canvas = skia::CreatePlatformCanvas(
306             skia_icon.width(), skia_icon.height(), false);
307         canvas->drawImage(skia_icon.bitmap()->asImage(), 0, 0);
308         DrawToNativeContext(
309             canvas.get(), dc, draw_item_struct->rcItem.left + kItemLeftMargin,
310             draw_item_struct->rcItem.top +
311                 (draw_item_struct->rcItem.bottom -
312                  draw_item_struct->rcItem.top - skia_icon.height()) /
313                     2,
314             NULL);
315       } else if (type == ui::MenuModel::TYPE_CHECK &&
316                  data->native_menu_win->model_->IsItemCheckedAt(
317                      data->model_index)) {
318         // Manually render a checkbox.
319         const MenuConfig& config = MenuConfig::instance();
320         NativeTheme::State state;
321         if (draw_item_struct->itemState & ODS_DISABLED) {
322           state = NativeTheme::kDisabled;
323         } else {
324           state = draw_item_struct->itemState & ODS_SELECTED
325                       ? NativeTheme::kHovered
326                       : NativeTheme::kNormal;
327         }
328 
329         std::unique_ptr<SkCanvas> canvas = skia::CreatePlatformCanvas(
330             config.check_width, config.check_height, false);
331         cc::SkiaPaintCanvas paint_canvas(canvas.get());
332 
333         NativeTheme::ExtraParams extra;
334         extra.menu_check.is_radio = false;
335         gfx::Rect bounds(0, 0, config.check_width, config.check_height);
336 
337         // Draw the background and the check.
338         ui::NativeTheme* native_theme =
339             ui::NativeTheme::GetInstanceForNativeUi();
340         native_theme->Paint(&paint_canvas, NativeTheme::kMenuCheckBackground,
341                             state, bounds, extra);
342         native_theme->Paint(&paint_canvas, NativeTheme::kMenuCheck, state,
343                             bounds, extra);
344 
345         // Draw checkbox to menu.
346         DrawToNativeContext(
347             canvas.get(), dc, draw_item_struct->rcItem.left + kItemLeftMargin,
348             draw_item_struct->rcItem.top +
349                 (draw_item_struct->rcItem.bottom -
350                  draw_item_struct->rcItem.top - config.check_height) /
351                     2,
352             NULL);
353       }
354     } else {
355       // Draw the separator
356       draw_item_struct->rcItem.top +=
357           (draw_item_struct->rcItem.bottom - draw_item_struct->rcItem.top) / 3;
358       DrawEdge(dc, &draw_item_struct->rcItem, EDGE_ETCHED, BF_TOP);
359     }
360 
361     SetBkColor(dc, prev_bg_color);
362     SetTextColor(dc, prev_text_color);
363   }
364 
ProcessWindowMessage(HWND window,UINT message,WPARAM w_param,LPARAM l_param,LRESULT * l_result)365   bool ProcessWindowMessage(HWND window,
366                             UINT message,
367                             WPARAM w_param,
368                             LPARAM l_param,
369                             LRESULT* l_result) {
370     switch (message) {
371       case WM_MENUCOMMAND:
372         OnMenuCommand(w_param, reinterpret_cast<HMENU>(l_param));
373         *l_result = 0;
374         return true;
375       case WM_MENUSELECT:
376         *l_result = 0;
377         return true;
378       case WM_MEASUREITEM:
379         OnMeasureItem(w_param, reinterpret_cast<MEASUREITEMSTRUCT*>(l_param));
380         *l_result = 0;
381         return true;
382       case WM_DRAWITEM:
383         OnDrawItem(w_param, reinterpret_cast<DRAWITEMSTRUCT*>(l_param));
384         *l_result = 0;
385         return true;
386         // TODO(beng): bring over owner draw from old menu system.
387     }
388     return false;
389   }
390 
MenuHostWindowProc(HWND window,UINT message,WPARAM w_param,LPARAM l_param)391   static LRESULT CALLBACK MenuHostWindowProc(HWND window,
392                                              UINT message,
393                                              WPARAM w_param,
394                                              LPARAM l_param) {
395     MenuHostWindow* host =
396         reinterpret_cast<MenuHostWindow*>(gfx::GetWindowUserData(window));
397     // host is null during initial construction.
398     LRESULT l_result = 0;
399     if (!host || !host->ProcessWindowMessage(window, message, w_param, l_param,
400                                              &l_result)) {
401       return DefWindowProc(window, message, w_param, l_param);
402     }
403     return l_result;
404   }
405 
406   HWND hwnd_;
407 
408   DISALLOW_COPY_AND_ASSIGN(MenuHostWindow);
409 };
410 
411 struct CefNativeMenuWin::HighlightedMenuItemInfo {
HighlightedMenuItemInfoviews::CefNativeMenuWin::HighlightedMenuItemInfo412   HighlightedMenuItemInfo()
413       : has_parent(false), has_submenu(false), menu(nullptr), position(-1) {}
414 
415   bool has_parent;
416   bool has_submenu;
417 
418   // The menu and position. These are only set for non-disabled menu items.
419   CefNativeMenuWin* menu;
420   int position;
421 };
422 
423 // static
424 const wchar_t* CefNativeMenuWin::MenuHostWindow::kWindowClassName =
425     L"ViewsMenuHostWindow";
426 
427 ////////////////////////////////////////////////////////////////////////////////
428 // CefNativeMenuWin, public:
429 
CefNativeMenuWin(ui::MenuModel * model,HWND system_menu_for)430 CefNativeMenuWin::CefNativeMenuWin(ui::MenuModel* model, HWND system_menu_for)
431     : model_(model),
432       menu_(nullptr),
433       owner_draw_(l10n_util::NeedOverrideDefaultUIFont(NULL, NULL) &&
434                   !system_menu_for),
435       system_menu_for_(system_menu_for),
436       first_item_index_(0),
437       menu_action_(MENU_ACTION_NONE),
438       menu_to_select_(nullptr),
439       position_to_select_(-1),
440       parent_(nullptr),
441       destroyed_flag_(nullptr),
442       menu_to_select_factory_(this) {}
443 
~CefNativeMenuWin()444 CefNativeMenuWin::~CefNativeMenuWin() {
445   if (destroyed_flag_)
446     *destroyed_flag_ = true;
447   DestroyMenu(menu_);
448 }
449 
450 ////////////////////////////////////////////////////////////////////////////////
451 // CefNativeMenuWin, MenuWrapper implementation:
452 
RunMenuAt(const gfx::Point & point,int alignment)453 void CefNativeMenuWin::RunMenuAt(const gfx::Point& point, int alignment) {
454   CreateHostWindow();
455   UpdateStates();
456   UINT flags = TPM_LEFTBUTTON | TPM_RIGHTBUTTON | TPM_RECURSE;
457   flags |= GetAlignmentFlags(alignment);
458   menu_action_ = MENU_ACTION_NONE;
459 
460   // Set a hook function so we can listen for keyboard events while the
461   // menu is open, and store a pointer to this object in a static
462   // variable so the hook has access to it (ugly, but it's the
463   // only way).
464   open_native_menu_win_ = this;
465   HHOOK hhook = SetWindowsHookEx(WH_MSGFILTER, MenuMessageHook,
466                                  GetModuleHandle(NULL), ::GetCurrentThreadId());
467 
468   // Command dispatch is done through WM_MENUCOMMAND, handled by the host
469   // window.
470   menu_to_select_ = nullptr;
471   position_to_select_ = -1;
472   menu_to_select_factory_.InvalidateWeakPtrs();
473   bool destroyed = false;
474   destroyed_flag_ = &destroyed;
475   model_->MenuWillShow();
476   TrackPopupMenu(menu_, flags, point.x(), point.y(), 0, host_window_->hwnd(),
477                  NULL);
478   UnhookWindowsHookEx(hhook);
479   open_native_menu_win_ = nullptr;
480   if (destroyed)
481     return;
482   destroyed_flag_ = nullptr;
483   if (menu_to_select_) {
484     // Folks aren't too happy if we notify immediately. In particular, notifying
485     // the delegate can cause destruction leaving the stack in a weird
486     // state. Instead post a task, then notify. This mirrors what WM_MENUCOMMAND
487     // does.
488     menu_to_select_factory_.InvalidateWeakPtrs();
489     base::ThreadTaskRunnerHandle::Get()->PostTask(
490         FROM_HERE, base::Bind(&CefNativeMenuWin::DelayedSelect,
491                               menu_to_select_factory_.GetWeakPtr()));
492     menu_action_ = MENU_ACTION_SELECTED;
493   }
494   // Send MenuWillClose after we schedule the select, otherwise MenuWillClose is
495   // processed after the select (MenuWillClose posts a delayed task too).
496   model_->MenuWillClose();
497 }
498 
CancelMenu()499 void CefNativeMenuWin::CancelMenu() {
500   EndMenu();
501 }
502 
Rebuild(MenuInsertionDelegateWin * delegate)503 void CefNativeMenuWin::Rebuild(MenuInsertionDelegateWin* delegate) {
504   ResetNativeMenu();
505   items_.clear();
506 
507   owner_draw_ = model_->HasIcons() || owner_draw_;
508   first_item_index_ = delegate ? delegate->GetInsertionIndex(menu_) : 0;
509   for (int menu_index = first_item_index_;
510        menu_index < first_item_index_ + model_->GetItemCount(); ++menu_index) {
511     int model_index = menu_index - first_item_index_;
512     if (model_->GetTypeAt(model_index) == ui::MenuModel::TYPE_SEPARATOR)
513       AddSeparatorItemAt(menu_index, model_index);
514     else
515       AddMenuItemAt(menu_index, model_index);
516   }
517 }
518 
UpdateStates()519 void CefNativeMenuWin::UpdateStates() {
520   // A depth-first walk of the menu items, updating states.
521   int model_index = 0;
522   ItemDataList::const_iterator it;
523   for (it = items_.begin(); it != items_.end(); ++it, ++model_index) {
524     int menu_index = model_index + first_item_index_;
525     SetMenuItemState(menu_index, model_->IsEnabledAt(model_index),
526                      model_->IsItemCheckedAt(model_index), false);
527     if (model_->IsItemDynamicAt(model_index)) {
528       // TODO(atwilson): Update the icon as well (http://crbug.com/66508).
529       SetMenuItemLabel(menu_index, model_index,
530                        base::UTF16ToWide(model_->GetLabelAt(model_index)));
531     }
532     Menu2* submenu = (*it)->submenu.get();
533     if (submenu)
534       submenu->UpdateStates();
535   }
536 }
537 
GetNativeMenu() const538 HMENU CefNativeMenuWin::GetNativeMenu() const {
539   return menu_;
540 }
541 
GetMenuAction() const542 CefNativeMenuWin::MenuAction CefNativeMenuWin::GetMenuAction() const {
543   return menu_action_;
544 }
545 
SetMinimumWidth(int width)546 void CefNativeMenuWin::SetMinimumWidth(int width) {
547   NOTIMPLEMENTED();
548 }
549 
550 ////////////////////////////////////////////////////////////////////////////////
551 // CefNativeMenuWin, private:
552 
553 // static
554 CefNativeMenuWin* CefNativeMenuWin::open_native_menu_win_ = nullptr;
555 
DelayedSelect()556 void CefNativeMenuWin::DelayedSelect() {
557   if (menu_to_select_)
558     menu_to_select_->model_->ActivatedAt(position_to_select_);
559 }
560 
561 // static
GetHighlightedMenuItemInfo(HMENU menu,HighlightedMenuItemInfo * info)562 bool CefNativeMenuWin::GetHighlightedMenuItemInfo(
563     HMENU menu,
564     HighlightedMenuItemInfo* info) {
565   for (int i = 0; i < ::GetMenuItemCount(menu); i++) {
566     UINT state = ::GetMenuState(menu, i, MF_BYPOSITION);
567     if (state & MF_HILITE) {
568       if (state & MF_POPUP) {
569         HMENU submenu = GetSubMenu(menu, i);
570         if (GetHighlightedMenuItemInfo(submenu, info))
571           info->has_parent = true;
572         else
573           info->has_submenu = true;
574       } else if (!(state & MF_SEPARATOR) && !(state & MF_DISABLED)) {
575         info->menu = GetCefNativeMenuWinFromHMENU(menu);
576         info->position = i;
577       }
578       return true;
579     }
580   }
581   return false;
582 }
583 
584 // static
MenuMessageHook(int n_code,WPARAM w_param,LPARAM l_param)585 LRESULT CALLBACK CefNativeMenuWin::MenuMessageHook(int n_code,
586                                                    WPARAM w_param,
587                                                    LPARAM l_param) {
588   LRESULT result = CallNextHookEx(NULL, n_code, w_param, l_param);
589 
590   CefNativeMenuWin* this_ptr = open_native_menu_win_;
591   if (!this_ptr)
592     return result;
593 
594   MSG* msg = reinterpret_cast<MSG*>(l_param);
595   if (msg->message == WM_LBUTTONUP || msg->message == WM_RBUTTONUP) {
596     HighlightedMenuItemInfo info;
597     if (GetHighlightedMenuItemInfo(this_ptr->menu_, &info) && info.menu) {
598       // It appears that when running a menu by way of TrackPopupMenu(Ex) win32
599       // gets confused if the underlying window paints itself. As its very easy
600       // for the underlying window to repaint itself (especially since some menu
601       // items trigger painting of the tabstrip on mouse over) we have this
602       // workaround. When the mouse is released on a menu item we remember the
603       // menu item and end the menu. When the nested message loop returns we
604       // schedule a task to notify the model. It's still possible to get a
605       // WM_MENUCOMMAND, so we have to be careful that we don't notify the model
606       // twice.
607       this_ptr->menu_to_select_ = info.menu;
608       this_ptr->position_to_select_ = info.position;
609       EndMenu();
610     }
611   } else if (msg->message == WM_KEYDOWN) {
612     HighlightedMenuItemInfo info;
613     if (GetHighlightedMenuItemInfo(this_ptr->menu_, &info)) {
614       if (msg->wParam == VK_LEFT && !info.has_parent) {
615         this_ptr->menu_action_ = MENU_ACTION_PREVIOUS;
616         ::EndMenu();
617       } else if (msg->wParam == VK_RIGHT && !info.has_parent &&
618                  !info.has_submenu) {
619         this_ptr->menu_action_ = MENU_ACTION_NEXT;
620         ::EndMenu();
621       }
622     }
623   }
624 
625   return result;
626 }
627 
IsSeparatorItemAt(int menu_index) const628 bool CefNativeMenuWin::IsSeparatorItemAt(int menu_index) const {
629   MENUITEMINFO mii = {0};
630   mii.cbSize = sizeof(mii);
631   mii.fMask = MIIM_FTYPE;
632   GetMenuItemInfo(menu_, menu_index, MF_BYPOSITION, &mii);
633   return !!(mii.fType & MF_SEPARATOR);
634 }
635 
AddMenuItemAt(int menu_index,int model_index)636 void CefNativeMenuWin::AddMenuItemAt(int menu_index, int model_index) {
637   MENUITEMINFO mii = {0};
638   mii.cbSize = sizeof(mii);
639   mii.fMask = MIIM_FTYPE | MIIM_ID | MIIM_DATA;
640   if (!owner_draw_)
641     mii.fType = MFT_STRING;
642   else
643     mii.fType = MFT_OWNERDRAW;
644 
645   std::unique_ptr<ItemData> item_data = std::make_unique<ItemData>();
646   item_data->label = std::wstring();
647   ui::MenuModel::ItemType type = model_->GetTypeAt(model_index);
648   if (type == ui::MenuModel::TYPE_SUBMENU) {
649     item_data->submenu.reset(new Menu2(model_->GetSubmenuModelAt(model_index)));
650     mii.fMask |= MIIM_SUBMENU;
651     mii.hSubMenu = item_data->submenu->GetNativeMenu();
652     GetCefNativeMenuWinFromHMENU(mii.hSubMenu)->parent_ = this;
653   } else {
654     if (type == ui::MenuModel::TYPE_RADIO)
655       mii.fType |= MFT_RADIOCHECK;
656     mii.wID = model_->GetCommandIdAt(model_index);
657   }
658   item_data->native_menu_win = this;
659   item_data->model_index = model_index;
660   mii.dwItemData = reinterpret_cast<ULONG_PTR>(item_data.get());
661   items_.insert(items_.begin() + model_index, std::move(item_data));
662   UpdateMenuItemInfoForString(
663       &mii, model_index, base::UTF16ToWide(model_->GetLabelAt(model_index)));
664   InsertMenuItem(menu_, menu_index, TRUE, &mii);
665 }
666 
AddSeparatorItemAt(int menu_index,int model_index)667 void CefNativeMenuWin::AddSeparatorItemAt(int menu_index, int model_index) {
668   MENUITEMINFO mii = {0};
669   mii.cbSize = sizeof(mii);
670   mii.fMask = MIIM_FTYPE;
671   mii.fType = MFT_SEPARATOR;
672   // Insert a dummy entry into our label list so we can index directly into it
673   // using item indices if need be.
674   items_.insert(items_.begin() + model_index, std::make_unique<ItemData>());
675   InsertMenuItem(menu_, menu_index, TRUE, &mii);
676 }
677 
SetMenuItemState(int menu_index,bool enabled,bool checked,bool is_default)678 void CefNativeMenuWin::SetMenuItemState(int menu_index,
679                                         bool enabled,
680                                         bool checked,
681                                         bool is_default) {
682   if (IsSeparatorItemAt(menu_index))
683     return;
684 
685   UINT state = enabled ? MFS_ENABLED : MFS_DISABLED;
686   if (checked)
687     state |= MFS_CHECKED;
688   if (is_default)
689     state |= MFS_DEFAULT;
690 
691   MENUITEMINFO mii = {0};
692   mii.cbSize = sizeof(mii);
693   mii.fMask = MIIM_STATE;
694   mii.fState = state;
695   SetMenuItemInfo(menu_, menu_index, MF_BYPOSITION, &mii);
696 }
697 
SetMenuItemLabel(int menu_index,int model_index,const std::wstring & label)698 void CefNativeMenuWin::SetMenuItemLabel(int menu_index,
699                                         int model_index,
700                                         const std::wstring& label) {
701   if (IsSeparatorItemAt(menu_index))
702     return;
703 
704   MENUITEMINFO mii = {0};
705   mii.cbSize = sizeof(mii);
706   UpdateMenuItemInfoForString(&mii, model_index, label);
707   SetMenuItemInfo(menu_, menu_index, MF_BYPOSITION, &mii);
708 }
709 
UpdateMenuItemInfoForString(MENUITEMINFO * mii,int model_index,const std::wstring & label)710 void CefNativeMenuWin::UpdateMenuItemInfoForString(MENUITEMINFO* mii,
711                                                    int model_index,
712                                                    const std::wstring& label) {
713   std::wstring formatted = label;
714   ui::MenuModel::ItemType type = model_->GetTypeAt(model_index);
715   // Strip out any tabs, otherwise they get interpreted as accelerators and can
716   // lead to weird behavior.
717   base::ReplaceSubstringsAfterOffset(&formatted, 0, L"\t", L" ");
718   if (type != ui::MenuModel::TYPE_SUBMENU) {
719     // Add accelerator details to the label if provided.
720     ui::Accelerator accelerator(ui::VKEY_UNKNOWN, ui::EF_NONE);
721     if (model_->GetAcceleratorAt(model_index, &accelerator)) {
722       formatted += L"\t";
723       formatted += base::UTF16ToWide(accelerator.GetShortcutText());
724     }
725   }
726 
727   // Update the owned string, since Windows will want us to keep this new
728   // version around.
729   items_[model_index]->label = formatted;
730 
731   // Give Windows a pointer to the label string.
732   mii->fMask |= MIIM_STRING;
733   mii->dwTypeData = const_cast<wchar_t*>(items_[model_index]->label.c_str());
734 }
735 
GetAlignmentFlags(int alignment) const736 UINT CefNativeMenuWin::GetAlignmentFlags(int alignment) const {
737   UINT alignment_flags = TPM_TOPALIGN;
738   if (alignment == Menu2::ALIGN_TOPLEFT)
739     alignment_flags |= TPM_LEFTALIGN;
740   else if (alignment == Menu2::ALIGN_TOPRIGHT)
741     alignment_flags |= TPM_RIGHTALIGN;
742   return alignment_flags;
743 }
744 
ResetNativeMenu()745 void CefNativeMenuWin::ResetNativeMenu() {
746   if (IsWindow(system_menu_for_)) {
747     if (menu_)
748       GetSystemMenu(system_menu_for_, TRUE);
749     menu_ = GetSystemMenu(system_menu_for_, FALSE);
750   } else {
751     if (menu_)
752       DestroyMenu(menu_);
753     menu_ = CreatePopupMenu();
754     // Rather than relying on the return value of TrackPopupMenuEx, which is
755     // always a command identifier, instead we tell the menu to notify us via
756     // our host window and the WM_MENUCOMMAND message.
757     MENUINFO mi = {0};
758     mi.cbSize = sizeof(mi);
759     mi.fMask = MIM_STYLE | MIM_MENUDATA;
760     mi.dwStyle = MNS_NOTIFYBYPOS;
761     mi.dwMenuData = reinterpret_cast<ULONG_PTR>(this);
762     SetMenuInfo(menu_, &mi);
763   }
764 }
765 
CreateHostWindow()766 void CefNativeMenuWin::CreateHostWindow() {
767   // This only gets called from RunMenuAt, and as such there is only ever one
768   // host window per menu hierarchy, no matter how many CefNativeMenuWin objects
769   // exist wrapping submenus.
770   if (!host_window_.get())
771     host_window_.reset(new MenuHostWindow());
772 }
773 
774 ////////////////////////////////////////////////////////////////////////////////
775 // MenuWrapper, public:
776 
777 // static
CreateWrapper(ui::MenuModel * model)778 MenuWrapper* MenuWrapper::CreateWrapper(ui::MenuModel* model) {
779   return new CefNativeMenuWin(model, NULL);
780 }
781 
782 }  // namespace views
783