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.
5 #include "ui/views/controls/menu/native_menu_win.h"
10 #include "base/logging.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/stl_util.h"
13 #include "base/strings/string_util.h"
14 #include "base/win/wrapped_window_proc.h"
15 #include "ui/base/accelerators/accelerator.h"
16 #include "ui/base/l10n/l10n_util.h"
17 #include "ui/base/l10n/l10n_util_win.h"
18 #include "ui/base/models/menu_model.h"
19 #include "ui/events/keycodes/keyboard_codes.h"
20 #include "ui/gfx/canvas.h"
21 #include "ui/gfx/font_list.h"
22 #include "ui/gfx/geometry/rect.h"
23 #include "ui/gfx/image/image.h"
24 #include "ui/gfx/image/image_skia.h"
25 #include "ui/gfx/text_utils.h"
26 #include "ui/gfx/win/hwnd_util.h"
27 #include "ui/native_theme/native_theme.h"
28 #include "ui/native_theme/native_theme_win.h"
29 #include "ui/views/controls/menu/menu_2.h"
30 #include "ui/views/controls/menu/menu_config.h"
31 #include "ui/views/controls/menu/menu_insertion_delegate_win.h"
32 #include "ui/views/controls/menu/menu_listener.h"
33 #include "ui/views/layout/layout_constants.h"
35 using ui::NativeTheme
;
39 // The width of an icon, including the pixels between the icon and
41 static const int kIconWidth
= 23;
42 // Margins between the top of the item and the label.
43 static const int kItemTopMargin
= 3;
44 // Margins between the bottom of the item and the label.
45 static const int kItemBottomMargin
= 4;
46 // Margins between the left of the item and the icon.
47 static const int kItemLeftMargin
= 4;
48 // The width for displaying the sub-menu arrow.
49 static const int kArrowWidth
= 10;
51 struct NativeMenuWin::ItemData
{
52 // The Windows API requires that whoever creates the menus must own the
53 // strings used for labels, and keep them around for the lifetime of the
54 // created menu. So be it.
57 // Someone needs to own submenus, it may as well be us.
58 scoped_ptr
<Menu2
> submenu
;
60 // We need a pointer back to the containing menu in various circumstances.
61 NativeMenuWin
* native_menu_win
;
63 // The index of the item within the menu's model.
67 // Returns the NativeMenuWin for a particular HMENU.
68 static NativeMenuWin
* GetNativeMenuWinFromHMENU(HMENU hmenu
) {
70 mi
.cbSize
= sizeof(mi
);
71 mi
.fMask
= MIM_MENUDATA
| MIM_STYLE
;
72 GetMenuInfo(hmenu
, &mi
);
73 return reinterpret_cast<NativeMenuWin
*>(mi
.dwMenuData
);
76 // A window that receives messages from Windows relevant to the native menu
77 // structure we have constructed in NativeMenuWin.
78 class NativeMenuWin::MenuHostWindow
{
80 explicit MenuHostWindow(NativeMenuWin
* parent
) : parent_(parent
) {
82 hwnd_
= CreateWindowEx(l10n_util::GetExtendedStyles(), kWindowClassName
,
83 L
"", 0, 0, 0, 0, 0, HWND_MESSAGE
, NULL
, NULL
, NULL
);
84 gfx::CheckWindowCreated(hwnd_
);
85 gfx::SetWindowUserData(hwnd_
, this);
92 HWND
hwnd() const { return hwnd_
; }
95 static const wchar_t* kWindowClassName
;
97 void RegisterClass() {
98 static bool registered
= false;
102 WNDCLASSEX window_class
;
103 base::win::InitializeWindowClass(
105 &base::win::WrappedWindowProc
<MenuHostWindowProc
>,
110 reinterpret_cast<HBRUSH
>(COLOR_WINDOW
+1),
115 ATOM clazz
= RegisterClassEx(&window_class
);
120 // Converts the WPARAM value passed to WM_MENUSELECT into an index
121 // corresponding to the menu item that was selected.
122 int GetMenuItemIndexFromWPARAM(HMENU menu
, WPARAM w_param
) const {
123 int count
= GetMenuItemCount(menu
);
124 // For normal command menu items, Windows passes a command id as the LOWORD
125 // of WPARAM for WM_MENUSELECT. We need to walk forward through the menu
126 // items to find an item with a matching ID. Ugh!
127 for (int i
= 0; i
< count
; ++i
) {
128 MENUITEMINFO mii
= {0};
129 mii
.cbSize
= sizeof(mii
);
131 GetMenuItemInfo(menu
, i
, MF_BYPOSITION
, &mii
);
132 if (mii
.wID
== w_param
)
135 // If we didn't find a matching command ID, this means a submenu has been
136 // selected instead, and rather than passing a command ID in
137 // LOWORD(w_param), Windows has actually passed us a position, so we just
142 NativeMenuWin::ItemData
* GetItemData(ULONG_PTR item_data
) {
143 return reinterpret_cast<NativeMenuWin::ItemData
*>(item_data
);
146 // Called when the user selects a specific item.
147 void OnMenuCommand(int position
, HMENU menu
) {
148 NativeMenuWin
* menu_win
= GetNativeMenuWinFromHMENU(menu
);
149 ui::MenuModel
* model
= menu_win
->model_
;
150 NativeMenuWin
* root_menu
= menu_win
;
151 while (root_menu
->parent_
)
152 root_menu
= root_menu
->parent_
;
154 // Only notify the model if it didn't already send out notification.
155 // See comment in MenuMessageHook for details.
156 if (root_menu
->menu_action_
== MenuWrapper::MENU_ACTION_NONE
)
157 model
->ActivatedAt(position
);
160 // Called as the user moves their mouse or arrows through the contents of the
162 void OnMenuSelect(WPARAM w_param
, HMENU menu
) {
164 return; // menu is null when closing on XP.
166 int position
= GetMenuItemIndexFromWPARAM(menu
, w_param
);
168 GetNativeMenuWinFromHMENU(menu
)->model_
->HighlightChangedTo(position
);
171 // Called by Windows to measure the size of an owner-drawn menu item.
172 void OnMeasureItem(WPARAM w_param
, MEASUREITEMSTRUCT
* measure_item_struct
) {
173 NativeMenuWin::ItemData
* data
= GetItemData(measure_item_struct
->itemData
);
175 gfx::FontList font_list
;
176 measure_item_struct
->itemWidth
=
177 gfx::GetStringWidth(data
->label
, font_list
) +
178 kIconWidth
+ kItemLeftMargin
+ views::kItemLabelSpacing
-
179 GetSystemMetrics(SM_CXMENUCHECK
);
180 if (data
->submenu
.get())
181 measure_item_struct
->itemWidth
+= kArrowWidth
;
182 // If the label contains an accelerator, make room for tab.
183 if (data
->label
.find(L
'\t') != base::string16::npos
)
184 measure_item_struct
->itemWidth
+= gfx::GetStringWidth(L
" ", font_list
);
185 measure_item_struct
->itemHeight
=
186 font_list
.GetHeight() + kItemBottomMargin
+ kItemTopMargin
;
188 // Measure separator size.
189 measure_item_struct
->itemHeight
= GetSystemMetrics(SM_CYMENU
) / 2;
190 measure_item_struct
->itemWidth
= 0;
194 // Called by Windows to paint an owner-drawn menu item.
195 void OnDrawItem(UINT w_param
, DRAWITEMSTRUCT
* draw_item_struct
) {
196 HDC dc
= draw_item_struct
->hDC
;
197 COLORREF prev_bg_color
, prev_text_color
;
199 // Set background color and text color
200 if (draw_item_struct
->itemState
& ODS_SELECTED
) {
201 prev_bg_color
= SetBkColor(dc
, GetSysColor(COLOR_HIGHLIGHT
));
202 prev_text_color
= SetTextColor(dc
, GetSysColor(COLOR_HIGHLIGHTTEXT
));
204 prev_bg_color
= SetBkColor(dc
, GetSysColor(COLOR_MENU
));
205 if (draw_item_struct
->itemState
& ODS_DISABLED
)
206 prev_text_color
= SetTextColor(dc
, GetSysColor(COLOR_GRAYTEXT
));
208 prev_text_color
= SetTextColor(dc
, GetSysColor(COLOR_MENUTEXT
));
211 if (draw_item_struct
->itemData
) {
212 NativeMenuWin::ItemData
* data
= GetItemData(draw_item_struct
->itemData
);
213 // Draw the background.
214 HBRUSH hbr
= CreateSolidBrush(GetBkColor(dc
));
215 FillRect(dc
, &draw_item_struct
->rcItem
, hbr
);
219 RECT rect
= draw_item_struct
->rcItem
;
220 rect
.top
+= kItemTopMargin
;
221 // Should we add kIconWidth only when icon.width() != 0 ?
222 rect
.left
+= kItemLeftMargin
+ kIconWidth
;
223 rect
.right
-= views::kItemLabelSpacing
;
224 UINT format
= DT_TOP
| DT_SINGLELINE
;
225 // Check whether the mnemonics should be underlined.
226 BOOL underline_mnemonics
;
227 SystemParametersInfo(SPI_GETKEYBOARDCUES
, 0, &underline_mnemonics
, 0);
228 if (!underline_mnemonics
)
229 format
|= DT_HIDEPREFIX
;
230 gfx::FontList font_list
;
231 HGDIOBJ old_font
= static_cast<HFONT
>(
232 SelectObject(dc
, font_list
.GetPrimaryFont().GetNativeFont()));
234 // If an accelerator is specified (with a tab delimiting the rest of the
235 // label from the accelerator), we have to justify the fist part on the
236 // left and the accelerator on the right.
237 // TODO(jungshik): This will break in RTL UI. Currently, he/ar use the
238 // window system UI font and will not hit here.
239 base::string16 label
= data
->label
;
240 base::string16 accel
;
241 base::string16::size_type tab_pos
= label
.find(L
'\t');
242 if (tab_pos
!= base::string16::npos
) {
243 accel
= label
.substr(tab_pos
);
244 label
= label
.substr(0, tab_pos
);
246 DrawTextEx(dc
, const_cast<wchar_t*>(label
.data()),
247 static_cast<int>(label
.size()), &rect
, format
| DT_LEFT
, NULL
);
249 DrawTextEx(dc
, const_cast<wchar_t*>(accel
.data()),
250 static_cast<int>(accel
.size()), &rect
,
251 format
| DT_RIGHT
, NULL
);
252 SelectObject(dc
, old_font
);
254 ui::MenuModel::ItemType type
=
255 data
->native_menu_win
->model_
->GetTypeAt(data
->model_index
);
257 // Draw the icon after the label, otherwise it would be covered
260 if (data
->native_menu_win
->model_
->GetIconAt(data
->model_index
, &icon
)) {
261 // We currently don't support items with both icons and checkboxes.
262 const gfx::ImageSkia
* skia_icon
= icon
.ToImageSkia();
263 DCHECK(type
!= ui::MenuModel::TYPE_CHECK
);
265 skia_icon
->GetRepresentation(1.0f
),
267 skia::DrawToNativeContext(
268 canvas
.sk_canvas(), dc
,
269 draw_item_struct
->rcItem
.left
+ kItemLeftMargin
,
270 draw_item_struct
->rcItem
.top
+ (draw_item_struct
->rcItem
.bottom
-
271 draw_item_struct
->rcItem
.top
- skia_icon
->height()) / 2, NULL
);
272 } else if (type
== ui::MenuModel::TYPE_CHECK
&&
273 data
->native_menu_win
->model_
->IsItemCheckedAt(
274 data
->model_index
)) {
275 // Manually render a checkbox.
276 ui::NativeThemeWin
* native_theme
= ui::NativeThemeWin::instance();
277 const MenuConfig
& config
= MenuConfig::instance(native_theme
);
278 NativeTheme::State state
;
279 if (draw_item_struct
->itemState
& ODS_DISABLED
) {
280 state
= NativeTheme::kDisabled
;
282 state
= draw_item_struct
->itemState
& ODS_SELECTED
?
283 NativeTheme::kHovered
: NativeTheme::kNormal
;
285 gfx::Canvas
canvas(gfx::Size(config
.check_width
, config
.check_height
),
288 NativeTheme::ExtraParams extra
;
289 extra
.menu_check
.is_radio
= false;
290 gfx::Rect
bounds(0, 0, config
.check_width
, config
.check_height
);
292 // Draw the background and the check.
294 canvas
.sk_canvas(), NativeTheme::kMenuCheckBackground
,
295 state
, bounds
, extra
);
297 canvas
.sk_canvas(), NativeTheme::kMenuCheck
, state
, bounds
, extra
);
299 // Draw checkbox to menu.
300 skia::DrawToNativeContext(canvas
.sk_canvas(), dc
,
301 draw_item_struct
->rcItem
.left
+ kItemLeftMargin
,
302 draw_item_struct
->rcItem
.top
+ (draw_item_struct
->rcItem
.bottom
-
303 draw_item_struct
->rcItem
.top
- config
.check_height
) / 2, NULL
);
307 // Draw the separator
308 draw_item_struct
->rcItem
.top
+=
309 (draw_item_struct
->rcItem
.bottom
- draw_item_struct
->rcItem
.top
) / 3;
310 DrawEdge(dc
, &draw_item_struct
->rcItem
, EDGE_ETCHED
, BF_TOP
);
313 SetBkColor(dc
, prev_bg_color
);
314 SetTextColor(dc
, prev_text_color
);
317 bool ProcessWindowMessage(HWND window
,
324 OnMenuCommand(w_param
, reinterpret_cast<HMENU
>(l_param
));
328 OnMenuSelect(LOWORD(w_param
), reinterpret_cast<HMENU
>(l_param
));
332 OnMeasureItem(w_param
, reinterpret_cast<MEASUREITEMSTRUCT
*>(l_param
));
336 OnDrawItem(w_param
, reinterpret_cast<DRAWITEMSTRUCT
*>(l_param
));
339 // TODO(beng): bring over owner draw from old menu system.
344 static LRESULT CALLBACK
MenuHostWindowProc(HWND window
,
348 MenuHostWindow
* host
=
349 reinterpret_cast<MenuHostWindow
*>(gfx::GetWindowUserData(window
));
350 // host is null during initial construction.
351 LRESULT l_result
= 0;
352 if (!host
|| !host
->ProcessWindowMessage(window
, message
, w_param
, l_param
,
354 return DefWindowProc(window
, message
, w_param
, l_param
);
360 NativeMenuWin
* parent_
;
362 DISALLOW_COPY_AND_ASSIGN(MenuHostWindow
);
365 struct NativeMenuWin::HighlightedMenuItemInfo
{
366 HighlightedMenuItemInfo()
376 // The menu and position. These are only set for non-disabled menu items.
382 const wchar_t* NativeMenuWin::MenuHostWindow::kWindowClassName
=
383 L
"ViewsMenuHostWindow";
385 ////////////////////////////////////////////////////////////////////////////////
386 // NativeMenuWin, public:
388 NativeMenuWin::NativeMenuWin(ui::MenuModel
* model
, HWND system_menu_for
)
391 owner_draw_(l10n_util::NeedOverrideDefaultUIFont(NULL
, NULL
) &&
393 system_menu_for_(system_menu_for
),
394 first_item_index_(0),
395 menu_action_(MENU_ACTION_NONE
),
396 menu_to_select_(NULL
),
397 position_to_select_(-1),
398 menu_to_select_factory_(this),
400 destroyed_flag_(NULL
) {
403 NativeMenuWin::~NativeMenuWin() {
405 *destroyed_flag_
= true;
406 STLDeleteContainerPointers(items_
.begin(), items_
.end());
410 ////////////////////////////////////////////////////////////////////////////////
411 // NativeMenuWin, MenuWrapper implementation:
413 void NativeMenuWin::RunMenuAt(const gfx::Point
& point
, int alignment
) {
416 UINT flags
= TPM_LEFTBUTTON
| TPM_RIGHTBUTTON
| TPM_RECURSE
;
417 flags
|= GetAlignmentFlags(alignment
);
418 menu_action_
= MENU_ACTION_NONE
;
420 // Set a hook function so we can listen for keyboard events while the
421 // menu is open, and store a pointer to this object in a static
422 // variable so the hook has access to it (ugly, but it's the
424 open_native_menu_win_
= this;
425 HHOOK hhook
= SetWindowsHookEx(WH_MSGFILTER
, MenuMessageHook
,
426 GetModuleHandle(NULL
), ::GetCurrentThreadId());
428 // Mark that any registered listeners have not been called for this particular
429 // opening of the menu.
430 listeners_called_
= false;
432 // Command dispatch is done through WM_MENUCOMMAND, handled by the host
434 menu_to_select_
= NULL
;
435 position_to_select_
= -1;
436 menu_to_select_factory_
.InvalidateWeakPtrs();
437 bool destroyed
= false;
438 destroyed_flag_
= &destroyed
;
439 model_
->MenuWillShow();
440 TrackPopupMenu(menu_
, flags
, point
.x(), point
.y(), 0, host_window_
->hwnd(),
442 UnhookWindowsHookEx(hhook
);
443 open_native_menu_win_
= NULL
;
446 destroyed_flag_
= NULL
;
447 if (menu_to_select_
) {
448 // Folks aren't too happy if we notify immediately. In particular, notifying
449 // the delegate can cause destruction leaving the stack in a weird
450 // state. Instead post a task, then notify. This mirrors what WM_MENUCOMMAND
452 menu_to_select_factory_
.InvalidateWeakPtrs();
453 base::MessageLoop::current()->PostTask(
455 base::Bind(&NativeMenuWin::DelayedSelect
,
456 menu_to_select_factory_
.GetWeakPtr()));
457 menu_action_
= MENU_ACTION_SELECTED
;
459 // Send MenuClosed after we schedule the select, otherwise MenuClosed is
460 // processed after the select (MenuClosed posts a delayed task too).
461 model_
->MenuClosed();
464 void NativeMenuWin::CancelMenu() {
468 void NativeMenuWin::Rebuild(MenuInsertionDelegateWin
* delegate
) {
472 owner_draw_
= model_
->HasIcons() || owner_draw_
;
473 first_item_index_
= delegate
? delegate
->GetInsertionIndex(menu_
) : 0;
474 for (int menu_index
= first_item_index_
;
475 menu_index
< first_item_index_
+ model_
->GetItemCount(); ++menu_index
) {
476 int model_index
= menu_index
- first_item_index_
;
477 if (model_
->GetTypeAt(model_index
) == ui::MenuModel::TYPE_SEPARATOR
)
478 AddSeparatorItemAt(menu_index
, model_index
);
480 AddMenuItemAt(menu_index
, model_index
);
484 void NativeMenuWin::UpdateStates() {
485 // A depth-first walk of the menu items, updating states.
487 std::vector
<ItemData
*>::const_iterator it
;
488 for (it
= items_
.begin(); it
!= items_
.end(); ++it
, ++model_index
) {
489 int menu_index
= model_index
+ first_item_index_
;
490 SetMenuItemState(menu_index
, model_
->IsEnabledAt(model_index
),
491 model_
->IsItemCheckedAt(model_index
), false);
492 if (model_
->IsItemDynamicAt(model_index
)) {
493 // TODO(atwilson): Update the icon as well (http://crbug.com/66508).
494 SetMenuItemLabel(menu_index
, model_index
,
495 model_
->GetLabelAt(model_index
));
497 Menu2
* submenu
= (*it
)->submenu
.get();
499 submenu
->UpdateStates();
503 HMENU
NativeMenuWin::GetNativeMenu() const {
507 NativeMenuWin::MenuAction
NativeMenuWin::GetMenuAction() const {
511 void NativeMenuWin::AddMenuListener(MenuListener
* listener
) {
512 listeners_
.AddObserver(listener
);
515 void NativeMenuWin::RemoveMenuListener(MenuListener
* listener
) {
516 listeners_
.RemoveObserver(listener
);
519 void NativeMenuWin::SetMinimumWidth(int width
) {
523 ////////////////////////////////////////////////////////////////////////////////
524 // NativeMenuWin, private:
527 NativeMenuWin
* NativeMenuWin::open_native_menu_win_
= NULL
;
529 void NativeMenuWin::DelayedSelect() {
531 menu_to_select_
->model_
->ActivatedAt(position_to_select_
);
535 bool NativeMenuWin::GetHighlightedMenuItemInfo(
537 HighlightedMenuItemInfo
* info
) {
538 for (int i
= 0; i
< ::GetMenuItemCount(menu
); i
++) {
539 UINT state
= ::GetMenuState(menu
, i
, MF_BYPOSITION
);
540 if (state
& MF_HILITE
) {
541 if (state
& MF_POPUP
) {
542 HMENU submenu
= GetSubMenu(menu
, i
);
543 if (GetHighlightedMenuItemInfo(submenu
, info
))
544 info
->has_parent
= true;
546 info
->has_submenu
= true;
547 } else if (!(state
& MF_SEPARATOR
) && !(state
& MF_DISABLED
)) {
548 info
->menu
= GetNativeMenuWinFromHMENU(menu
);
558 LRESULT CALLBACK
NativeMenuWin::MenuMessageHook(
559 int n_code
, WPARAM w_param
, LPARAM l_param
) {
560 LRESULT result
= CallNextHookEx(NULL
, n_code
, w_param
, l_param
);
562 NativeMenuWin
* this_ptr
= open_native_menu_win_
;
566 // The first time this hook is called, that means the menu has successfully
567 // opened, so call the callback function on all of our listeners.
568 if (!this_ptr
->listeners_called_
) {
569 FOR_EACH_OBSERVER(MenuListener
, this_ptr
->listeners_
, OnMenuOpened());
570 this_ptr
->listeners_called_
= true;
573 MSG
* msg
= reinterpret_cast<MSG
*>(l_param
);
574 if (msg
->message
== WM_LBUTTONUP
|| msg
->message
== WM_RBUTTONUP
) {
575 HighlightedMenuItemInfo info
;
576 if (GetHighlightedMenuItemInfo(this_ptr
->menu_
, &info
) && info
.menu
) {
577 // It appears that when running a menu by way of TrackPopupMenu(Ex) win32
578 // gets confused if the underlying window paints itself. As its very easy
579 // for the underlying window to repaint itself (especially since some menu
580 // items trigger painting of the tabstrip on mouse over) we have this
581 // workaround. When the mouse is released on a menu item we remember the
582 // menu item and end the menu. When the nested message loop returns we
583 // schedule a task to notify the model. It's still possible to get a
584 // WM_MENUCOMMAND, so we have to be careful that we don't notify the model
586 this_ptr
->menu_to_select_
= info
.menu
;
587 this_ptr
->position_to_select_
= info
.position
;
590 } else if (msg
->message
== WM_KEYDOWN
) {
591 HighlightedMenuItemInfo info
;
592 if (GetHighlightedMenuItemInfo(this_ptr
->menu_
, &info
)) {
593 if (msg
->wParam
== VK_LEFT
&& !info
.has_parent
) {
594 this_ptr
->menu_action_
= MENU_ACTION_PREVIOUS
;
596 } else if (msg
->wParam
== VK_RIGHT
&& !info
.has_parent
&&
598 this_ptr
->menu_action_
= MENU_ACTION_NEXT
;
607 bool NativeMenuWin::IsSeparatorItemAt(int menu_index
) const {
608 MENUITEMINFO mii
= {0};
609 mii
.cbSize
= sizeof(mii
);
610 mii
.fMask
= MIIM_FTYPE
;
611 GetMenuItemInfo(menu_
, menu_index
, MF_BYPOSITION
, &mii
);
612 return !!(mii
.fType
& MF_SEPARATOR
);
615 void NativeMenuWin::AddMenuItemAt(int menu_index
, int model_index
) {
616 MENUITEMINFO mii
= {0};
617 mii
.cbSize
= sizeof(mii
);
618 mii
.fMask
= MIIM_FTYPE
| MIIM_ID
| MIIM_DATA
;
620 mii
.fType
= MFT_STRING
;
622 mii
.fType
= MFT_OWNERDRAW
;
624 ItemData
* item_data
= new ItemData
;
625 item_data
->label
= base::string16();
626 ui::MenuModel::ItemType type
= model_
->GetTypeAt(model_index
);
627 if (type
== ui::MenuModel::TYPE_SUBMENU
) {
628 item_data
->submenu
.reset(new Menu2(model_
->GetSubmenuModelAt(model_index
)));
629 mii
.fMask
|= MIIM_SUBMENU
;
630 mii
.hSubMenu
= item_data
->submenu
->GetNativeMenu();
631 GetNativeMenuWinFromHMENU(mii
.hSubMenu
)->parent_
= this;
633 if (type
== ui::MenuModel::TYPE_RADIO
)
634 mii
.fType
|= MFT_RADIOCHECK
;
635 mii
.wID
= model_
->GetCommandIdAt(model_index
);
637 item_data
->native_menu_win
= this;
638 item_data
->model_index
= model_index
;
639 items_
.insert(items_
.begin() + model_index
, item_data
);
640 mii
.dwItemData
= reinterpret_cast<ULONG_PTR
>(item_data
);
641 UpdateMenuItemInfoForString(&mii
, model_index
,
642 model_
->GetLabelAt(model_index
));
643 InsertMenuItem(menu_
, menu_index
, TRUE
, &mii
);
646 void NativeMenuWin::AddSeparatorItemAt(int menu_index
, int model_index
) {
647 MENUITEMINFO mii
= {0};
648 mii
.cbSize
= sizeof(mii
);
649 mii
.fMask
= MIIM_FTYPE
;
650 mii
.fType
= MFT_SEPARATOR
;
651 // Insert a dummy entry into our label list so we can index directly into it
652 // using item indices if need be.
653 items_
.insert(items_
.begin() + model_index
, new ItemData
);
654 InsertMenuItem(menu_
, menu_index
, TRUE
, &mii
);
657 void NativeMenuWin::SetMenuItemState(int menu_index
, bool enabled
, bool checked
,
659 if (IsSeparatorItemAt(menu_index
))
662 UINT state
= enabled
? MFS_ENABLED
: MFS_DISABLED
;
664 state
|= MFS_CHECKED
;
666 state
|= MFS_DEFAULT
;
668 MENUITEMINFO mii
= {0};
669 mii
.cbSize
= sizeof(mii
);
670 mii
.fMask
= MIIM_STATE
;
672 SetMenuItemInfo(menu_
, menu_index
, MF_BYPOSITION
, &mii
);
675 void NativeMenuWin::SetMenuItemLabel(int menu_index
,
677 const base::string16
& label
) {
678 if (IsSeparatorItemAt(menu_index
))
681 MENUITEMINFO mii
= {0};
682 mii
.cbSize
= sizeof(mii
);
683 UpdateMenuItemInfoForString(&mii
, model_index
, label
);
684 SetMenuItemInfo(menu_
, menu_index
, MF_BYPOSITION
, &mii
);
687 void NativeMenuWin::UpdateMenuItemInfoForString(MENUITEMINFO
* mii
,
689 const base::string16
& label
) {
690 base::string16 formatted
= label
;
691 ui::MenuModel::ItemType type
= model_
->GetTypeAt(model_index
);
692 // Strip out any tabs, otherwise they get interpreted as accelerators and can
693 // lead to weird behavior.
694 ReplaceSubstringsAfterOffset(&formatted
, 0, L
"\t", L
" ");
695 if (type
!= ui::MenuModel::TYPE_SUBMENU
) {
696 // Add accelerator details to the label if provided.
697 ui::Accelerator
accelerator(ui::VKEY_UNKNOWN
, ui::EF_NONE
);
698 if (model_
->GetAcceleratorAt(model_index
, &accelerator
)) {
700 formatted
+= accelerator
.GetShortcutText();
704 // Update the owned string, since Windows will want us to keep this new
706 items_
[model_index
]->label
= formatted
;
708 // Give Windows a pointer to the label string.
709 mii
->fMask
|= MIIM_STRING
;
711 const_cast<wchar_t*>(items_
[model_index
]->label
.c_str());
714 UINT
NativeMenuWin::GetAlignmentFlags(int alignment
) const {
715 UINT alignment_flags
= TPM_TOPALIGN
;
716 if (alignment
== Menu2::ALIGN_TOPLEFT
)
717 alignment_flags
|= TPM_LEFTALIGN
;
718 else if (alignment
== Menu2::ALIGN_TOPRIGHT
)
719 alignment_flags
|= TPM_RIGHTALIGN
;
720 return alignment_flags
;
723 void NativeMenuWin::ResetNativeMenu() {
724 if (IsWindow(system_menu_for_
)) {
726 GetSystemMenu(system_menu_for_
, TRUE
);
727 menu_
= GetSystemMenu(system_menu_for_
, FALSE
);
731 menu_
= CreatePopupMenu();
732 // Rather than relying on the return value of TrackPopupMenuEx, which is
733 // always a command identifier, instead we tell the menu to notify us via
734 // our host window and the WM_MENUCOMMAND message.
736 mi
.cbSize
= sizeof(mi
);
737 mi
.fMask
= MIM_STYLE
| MIM_MENUDATA
;
738 mi
.dwStyle
= MNS_NOTIFYBYPOS
;
739 mi
.dwMenuData
= reinterpret_cast<ULONG_PTR
>(this);
740 SetMenuInfo(menu_
, &mi
);
744 void NativeMenuWin::CreateHostWindow() {
745 // This only gets called from RunMenuAt, and as such there is only ever one
746 // host window per menu hierarchy, no matter how many NativeMenuWin objects
747 // exist wrapping submenus.
748 if (!host_window_
.get())
749 host_window_
.reset(new MenuHostWindow(this));
752 ////////////////////////////////////////////////////////////////////////////////
753 // MenuWrapper, public:
756 MenuWrapper
* MenuWrapper::CreateWrapper(ui::MenuModel
* model
) {
757 return new NativeMenuWin(model
, NULL
);