15 private readonly
View _view;
16 private readonly Rectangle _bounds;
18 private readonly DismissLayerWidget _dismissLayer;
19 private readonly List<MenuBarMenu> _menus =
new();
21 private readonly Dictionary<string, MenuItemWidget> _itemsByKey =
new(StringComparer.Ordinal);
22 private readonly Dictionary<KeyGesture, MenuItemWidget> _shortcuts =
new();
39 _itemsByKey.TryGetValue(key, out item);
41 internal void ValidateRegistration(
string? key,
KeyGesture? shortcut)
43 ObjectDisposedException.ThrowIf(_disposed,
this);
47 ArgumentException.ThrowIfNullOrWhiteSpace(key);
49 if (_itemsByKey.ContainsKey(key))
50 throw new ArgumentException($
"Duplicate menu item key '{key}'.", nameof(key));
53 if (shortcut is { } gesture)
56 throw new ArgumentException(
"A shortcut requires a nonzero key.", nameof(shortcut));
58 if (_shortcuts.ContainsKey(gesture))
59 throw new ArgumentException($
"Duplicate menu shortcut '{gesture}'.", nameof(shortcut));
65 if (item.
Key is not
null)
66 _itemsByKey.Add(item.
Key, item);
69 _shortcuts.Add(gesture, item);
72 internal void UnregisterItem(MenuItemWidget item)
74 if (item.Key is not
null && _itemsByKey.GetValueOrDefault(item.Key) == item)
75 _itemsByKey.Remove(item.Key);
77 if (item.Shortcut is { } gesture && _shortcuts.GetValueOrDefault(gesture) == item)
78 _shortcuts.Remove(gesture);
82 private int _openMenuIndex = -1;
83 private int _nextHeaderX;
84 private int _menuZOrder = 20_000;
85 private bool _disposed;
109 string? nickname =
null)
116 ArgumentNullException.ThrowIfNull(view);
118 if (bounds.Width <= 0 || bounds.Height <= 0)
120 throw new ArgumentOutOfRangeException(
123 "Menu bar bounds must have positive width and height.");
129 _nextHeaderX = bounds.X;
132 _theme.BarBackgroundColor,
136 $
"{Nickname}.background")
143 _dismissLayer =
new DismissLayerWidget(
147 $
"{Nickname}.dismiss");
149 _dismissLayer.DismissRequested += OnDismissRequested;
150 _dismissLayer.SetDismissEnabled(
false);
155 dismissBounds.X - bounds.X,
156 dismissBounds.Y - bounds.Y));
171 public IReadOnlyList<MenuBarMenu>
Menus => _menus.AsReadOnly();
178 _openMenuIndex >= 0 && _openMenuIndex < _menus.Count
179 ? _menus[_openMenuIndex]
199 Action<MenuDropDownWidget>? configure =
null,
200 int? headerWidth =
null,
201 char? mnemonic =
null)
203 ObjectDisposedException.ThrowIf(_disposed,
this);
204 ArgumentNullException.ThrowIfNull(text);
206 if (mnemonic is
char character && _menus.Any(menu => menu.Header.Mnemonic is
char existing &&
207 char.ToUpperInvariant(existing) ==
208 char.ToUpperInvariant(character)))
209 throw new ArgumentException($
"Duplicate top-level mnemonic '{character}'.", nameof(mnemonic));
211 int resolvedHeaderWidth = headerWidth ?? EstimateHeaderWidth(text);
213 if (resolvedHeaderWidth <= 0)
215 throw new ArgumentOutOfRangeException(
218 "Menu header width must be positive.");
221 var headerBounds =
new Rectangle(
227 int menuIndex = _menus.Count;
235 $
"{Nickname}.header.{menuIndex}",
241 new Point(headerBounds.X, _bounds.Bottom),
243 $
"{Nickname}.dropdown.{menuIndex}",
248 configure?.Invoke(dropDown);
257 PositionDropDown(headerBounds, dropDown);
262 header.Invoked += OnHeaderInvoked;
263 header.Hovered += OnHeaderHovered;
268 headerBounds.X - _bounds.X,
269 headerBounds.Y - _bounds.Y));
274 dropDown.GetPosition().X - _bounds.X,
275 dropDown.GetPosition().Y - _bounds.Y));
280 _nextHeaderX += resolvedHeaderWidth;
281 ApplyMenuZOrder(_menuZOrder);
290 if (index < 0 || index >= _menus.Count)
291 throw new ArgumentOutOfRangeException(nameof(index));
293 if (!IsAvailable || _openMenuIndex == index)
296 CloseMenuInternal(immediate:
true);
298 _previousFocus = WidgetInputRouterRegistry.GetFocusedWidget(
this);
299 _openMenuIndex = index;
302 menu.
Header.SetOpen(
true);
305 candidate.
Header.SetMenuBarActive(
true);
307 _dismissLayer.SetDismissEnabled(
true);
311 WidgetInputRouterRegistry.TryBringToFront(
this);
312 _dismissLayer.Activate();
317 PositionDropDown(menu.Header.Background.ScreenBounds, menu.DropDown);
318 WidgetInputRouterRegistry.TryFocus(menu.Header);
320 menu.DropDown.OpenAnimated(
324 menu.DropDown.Activate();
325 menu.DropDown.SelectFirstEnabled();
333 CloseMenuInternal(immediate:
false);
340 if (_openMenuIndex == index)
351 _menuZOrder = zOrder;
352 ApplyMenuZOrder(_menuZOrder);
361 _dismissLayer.SetDismissEnabled(
false);
366 menu.
Header.SetOpen(
false);
367 menu.
Header.SetMenuBarActive(
false);
375 CloseMenuInternal(immediate:
true);
376 _dismissLayer.SetDismissEnabled(
false);
377 base.ProcessHidden();
383 base.OnKeyboardInput(args);
384 HandleKeyboard(args);
387 void IWidgetKeyboardFallback.HandleUnhandledKeyboardInput(
WidgetKeyboardEventArgs args) => HandleKeyboard(args);
398 command.PerformClick();
404 int index = _menus.FindIndex(menu => MatchesMnemonic(menu.
Header.
Mnemonic, args.
Key));
410 _menus[index].DropDown.SelectFirstEnabled();
418 var dropDown = _menus[_openMenuIndex].DropDown.ActiveMenu;
423 if (dropDown.ParentMenu is { } parent)
430 if (dropDown.ParentMenu is { } previous)
431 previous.CloseChild();
433 OpenMenuAt((_openMenuIndex - 1 + _menus.Count) % _menus.Count);
437 if (dropDown.SelectedItem is { SubMenu: not null } owner)
438 dropDown.OpenSubMenu(owner, selectFirst:
true);
439 else if (dropDown.ParentMenu is
null)
440 OpenMenuAt((_openMenuIndex + 1) % _menus.Count);
444 dropDown.SelectPreviousEnabled();
447 dropDown.SelectNextEnabled();
451 dropDown.InvokeSelectedItem();
454 var item = dropDown.Items.FirstOrDefault(item =>
455 item.CanInvoke && MatchesMnemonic(item.Mnemonic, args.
Key));
467 private static bool MatchesMnemonic(
char? mnemonic,
int key) => mnemonic is
char character &&
468 key <= char.MaxValue && key >= 0 &&
469 char.ToUpperInvariant(character) ==
470 char.ToUpperInvariant((
char)key);
479 CloseMenuInternal(immediate:
true);
481 _dismissLayer.DismissRequested -= OnDismissRequested;
485 menu.Header.Invoked -= OnHeaderInvoked;
486 menu.Header.Hovered -= OnHeaderHovered;
497 int index = _menus.FindIndex(menu => ReferenceEquals(menu.
Header, header));
503 private void OnHeaderHovered(MenuHeaderWidget header)
505 if (_openMenuIndex < 0)
508 int index = _menus.FindIndex(menu => ReferenceEquals(menu.
Header, header));
510 if (index >= 0 && index != _openMenuIndex)
514 internal void OnItemInvoked(MenuItemWidget item)
516 CloseMenuInternal(immediate:
true);
520 private void OnDismissRequested()
525 private void CloseMenuInternal(
bool immediate)
527 if (_openMenuIndex < 0 || _openMenuIndex >= _menus.Count)
529 _dismissLayer.SetDismissEnabled(
false);
534 MenuBarMenu menu = _menus[_openMenuIndex];
537 menu.
Header.SetOpen(
false);
539 foreach (MenuBarMenu candidate
in _menus)
540 candidate.Header.SetMenuBarActive(
false);
542 _dismissLayer.SetDismissEnabled(
false);
544 menu.DropDown.CloseAnimated(
549 var focused = WidgetInputRouterRegistry.GetFocusedWidget(
this);
551 if (focused is
null || ContainsWidget(
this, focused))
552 WidgetInputRouterRegistry.RestoreFocus(
this, _previousFocus);
554 _previousFocus =
null;
559 container.ChildWidgets.Any(child => ReferenceEquals(child, widget) ||
562 private void PositionDropDown(
563 Rectangle headerBounds,
564 MenuDropDownWidget dropDown)
566 Rectangle viewport = _view.Viewport.TargetRectPx;
571 Math.Max(viewport.Left, viewport.Right - dropDown.Width));
573 int y = Math.Clamp(_bounds.Bottom, viewport.Top, Math.Max(viewport.Top, viewport.Bottom - dropDown.Height));
578 dropDown.SetPosition(x, y);
581 private int EstimateHeaderWidth(
string text)
583 int estimatedTextWidth = (int)Math.Ceiling(
584 text.Length * _theme.EstimatedGlyphWidth);
587 _theme.MinimumHeaderWidth,
588 estimatedTextWidth + (_theme.HeaderHorizontalPadding * 2));
591 private void ApplyMenuZOrder(
int zOrder)
593 _dismissLayer.SetLayerZOrder(zOrder);
594 BarBackground.ZOrder = zOrder + 1;
596 foreach (MenuBarMenu menu
in _menus)
598 menu.Header.SetHeaderZOrder(zOrder + 2);
599 menu.DropDown.SetDropDownZOrder(zOrder + 10);
603 private sealed class DismissLayerWidget :
WidgetBase
605 internal event Action? DismissRequested;
607 internal DismissLayerWidget(
608 RenderSurfaceHostBase host,
618 HitArea =
new DirectRectangle(
623 $
"{Nickname}.hit-area")
633 internal DirectRectangle HitArea {
get; }
635 internal void SetDismissEnabled(
bool enabled)
646 internal void SetLayerZOrder(
int zOrder)
648 HitArea.ZOrder = zOrder;
652 protected override void OnPointerClick(WidgetPointerEventArgs args)
654 base.OnPointerClick(args);
656 if (!args.IsPrimaryButton)
660 DismissRequested?.Invoke();