using Mindmagma.Curses; using System.Collections.ObjectModel; namespace SCI.CursesWrapper.UiElements; public class TopMenu : Window { private List _menuItems = new List (); public ReadOnlyCollection MenuItems { get { return _menuItems.AsReadOnly (); } } private MenuItem? activeMenuItem; /// /// Class constructor /// /// /// /// public TopMenu (nint screen, InputHandler targetInputHandler, List menuItems) : base (0, 0, CursesWrapper.GetWidth (screen), 1, targetInputHandler) { var colorSchemeNormal = ColorSchemes.TopMenuNormal (); BackgroundColorId = colorSchemeNormal; NCurses.WindowAttributeOn (WindowId, colorSchemeNormal); _menuItems = menuItems; foreach (var item in menuItems) { item.AssignParentTopMenuWindow (this); } RegisterItemEventHandlers (); DrawMenu (); } /// /// Finalizer, clean up event handlers /// ~TopMenu () { UnregisterItemEventHandlers (); Destroy (); } /// /// Register key event handlers for each menu item /// private void RegisterItemEventHandlers () { if (TargetInputHandler is null) return; foreach (var item in MenuItems) { item.OnItemActivated += ItemActivatedHandler; TargetInputHandler.OnKeyPressPrivileged += item.KeypressHandler; } } /// /// Unregister key event handlers for each menu item /// private void UnregisterItemEventHandlers () { if (TargetInputHandler is null) return; foreach (var item in MenuItems) { item.OnItemActivated -= ItemActivatedHandler; OnKeyPress -= item.KeypressHandler; } } /// /// Event handler to update menu interface when item reports itself as activated /// /// Sender Menu Item firing the event /// Event arguments private void ItemActivatedHandler (object? sender, EventArgs e) { if (sender is null) return; activeMenuItem = (MenuItem) sender; DrawMenu (); } /// /// /// /// public void ActivateItem (MenuItem item) { foreach (var myItem in MenuItems) { if (myItem == item) { ItemActivatedHandler (myItem, EventArgs.Empty); myItem.ActivateItem (); return; } } throw new Exception ("This item does not exist"); } /// /// Draw the top menu with currently configured menu items /// private void DrawMenu () { NCurses.ClearWindow (WindowId); var normalColor = ColorSchemes.TopMenuNormal (); var activeColor = ColorSchemes.TopMenuActive (); foreach (var item in MenuItems) { var itemIsActive = item == activeMenuItem; var itemString = " "; if (itemIsActive) { itemString = "["; NCurses.WindowAttributeOff (WindowId, normalColor); NCurses.WindowAttributeOn (WindowId, activeColor); } itemString += $"{item.Label}"; if (item.Key is not null) { itemString += $" ({item.Key})"; } if (itemIsActive) { NCurses.WindowAttributeOff (WindowId, activeColor); NCurses.WindowAttributeOn (WindowId, normalColor); itemString += "] "; } else { itemString += " "; } NCurses.WindowAddString (WindowId, itemString); } Draw (); } }