using SCI.CursesWrapper; using Mindmagma.Curses; namespace ANSI_Fahrplan.UiElements; public class TopMenu : UiElement { private List _menuItems = new List (); public List MenuItems { get { return _menuItems; } set { UnregisterItemEventHandlers (); _menuItems = value; RegisterItemEventHandlers (); DrawMenu (); } } private MenuItem? activeMenuItem; public TopMenu (nint screen, List menuItems) : base (screen) { NCurses.GetMaxYX (screen, out _, out int width); innerWindow = NCurses.NewWindow (1, width, 0, 0); var colorSchemeNormal = ColorSchemes.TopMenuNormal (); NCurses.WindowBackground (innerWindow, colorSchemeNormal); NCurses.WindowAttributeOn (innerWindow, colorSchemeNormal); MenuItems = menuItems; } /// /// Register key event handlers for each menu item /// private void RegisterItemEventHandlers () { foreach (var item in MenuItems) { item.OnItemActivated += ItemActivatedHandler; item.RegisterKeyHandler (); } } /// /// Unregister key event handlers for each menu item /// private void UnregisterItemEventHandlers () { foreach (var item in MenuItems) { item.OnItemActivated -= ItemActivatedHandler; item.UnregisterKeyHandler (); } } /// /// 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 (); } /// /// Draw the top menu with currently configured menu items /// private void DrawMenu () { NCurses.ClearWindow (innerWindow); var normalColor = ColorSchemes.TopMenuNormal (); var activeColor = ColorSchemes.TopMenuActive (); foreach (var item in MenuItems) { var itemIsActive = item == activeMenuItem; var itemString = " "; if (itemIsActive) { itemString = "["; NCurses.WindowAttributeOff (innerWindow, normalColor); NCurses.WindowAttributeOn (innerWindow, activeColor); } itemString += $"{item.Label}"; if (item.Key is not null) { itemString += $" ({item.Key})"; } if (itemIsActive) { NCurses.WindowAttributeOff (innerWindow, activeColor); NCurses.WindowAttributeOn (innerWindow, normalColor); itemString += "] "; } else { itemString += " "; } NCurses.WindowAddString (innerWindow, itemString); } NCurses.Refresh (); NCurses.WindowRefresh (innerWindow); } public void Refresh () { DrawMenu (); } }