//
// Menu.cs: application menus and submenus
//
// Authors:
// Miguel de Icaza (miguel@gnome.org)
//
// TODO:
// Add accelerator support, but should also support chords (ShortCut in MenuItem)
// Allow menus inside menus
using System;
using NStack;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
namespace Terminal.Gui {
///
/// A has a title, an associated help text, and an action to execute on activation.
///
public class MenuItem {
///
/// Initializes a new instance of
///
public MenuItem ()
{
Title = "";
Help = "";
}
///
/// Initializes a new instance of .
///
/// Title for the menu item.
/// Help text to display.
/// Action to invoke when the menu item is activated.
/// Function to determine if the action can currently be executred.
public MenuItem (ustring title, string help, Action action, Func canExecute = null)
{
Title = title ?? "";
Help = help ?? "";
Action = action;
CanExecute = canExecute;
bool nextIsHot = false;
foreach (var x in Title) {
if (x == '_')
nextIsHot = true;
else {
if (nextIsHot) {
HotKey = Char.ToUpper ((char)x);
break;
}
nextIsHot = false;
}
}
}
///
/// Initializes a new instance of
///
/// Title for the menu item.
/// The menu sub-menu.
public MenuItem (ustring title, MenuBarItem subMenu) : this (title, "", null)
{
SubMenu = subMenu;
IsFromSubMenu = true;
}
///
/// The HotKey is used when the menu is active, the shortcut can be triggered when the menu is not active.
/// For example HotKey would be "N" when the File Menu is open (assuming there is a "_New" entry
/// if the ShortCut is set to "Control-N", this would be a global hotkey that would trigger as well
///
public Rune HotKey;
///
/// This is the global setting that can be used as a global shortcut to invoke the action on the menu.
///
public Key ShortCut;
///
/// Gets or sets the title.
///
/// The title.
public ustring Title { get; set; }
///
/// Gets or sets the help text for the menu item.
///
/// The help text.
public ustring Help { get; set; }
///
/// Gets or sets the action to be invoked when the menu is triggered
///
/// Method to invoke.
public Action Action { get; set; }
///
/// Gets or sets the action to be invoked if the menu can be triggered
///
/// Function to determine if action is ready to be executed.
public Func CanExecute { get; set; }
///
/// Shortcut to check if the menu item is enabled
///
public bool IsEnabled ()
{
return CanExecute == null ? true : CanExecute ();
}
internal int Width => Title.Length + Help.Length + 1 + 2;
///
/// Gets or sets the parent for this
///
/// The parent.
internal MenuBarItem SubMenu { get; set; }
internal bool IsFromSubMenu { get; set; }
///
/// Merely a debugging aid to see the interaction with main
///
public MenuItem GetMenuItem ()
{
return this;
}
///
/// Merely a debugging aid to see the interaction with main
///
public bool GetMenuBarItem ()
{
return IsFromSubMenu;
}
}
///
/// A contains s or s.
///
public class MenuBarItem : MenuItem {
///
/// Initializes a new as a .
///
/// Title for the menu item.
/// Help text to display.
/// Action to invoke when the menu item is activated.
/// Function to determine if the action can currently be executred.
public MenuBarItem (ustring title, string help, Action action, Func canExecute = null) : base (title, help, action, canExecute)
{
SetTitle (title ?? "");
Children = null;
}
///
/// Initializes a new .
///
/// Title for the menu item.
/// The items in the current menu.
public MenuBarItem (ustring title, MenuItem [] children)
{
if (children == null)
throw new ArgumentNullException (nameof (children), "The parameter cannot be null. Use an empty array instead.");
SetTitle (title ?? "");
Children = children;
}
///
/// Initializes a new .
///
/// The items in the current menu.
public MenuBarItem (MenuItem [] children) : this (new string (' ', GetMaxTitleLength (children)), children)
{
}
static int GetMaxTitleLength (MenuItem [] children)
{
int maxLength = 0;
foreach (var item in children) {
int len = GetMenuBarItemLength (item.Title);
if (len > maxLength)
maxLength = len;
item.IsFromSubMenu = true;
}
return maxLength;
}
void SetTitle (ustring title)
{
if (title == null)
title = "";
Title = title;
TitleLength = GetMenuBarItemLength (Title);
}
static int GetMenuBarItemLength (ustring title)
{
int len = 0;
foreach (var ch in title) {
if (ch == '_')
continue;
len++;
}
return len;
}
/////
///// Gets or sets the title to display.
/////
///// The title.
//public ustring Title { get; set; }
///
/// Gets or sets an array of objects that are the children of this
///
/// The children.
public MenuItem [] Children { get; set; }
internal int TitleLength { get; private set; }
internal bool IsTopLevel { get => (Children == null || Children.Length == 0); }
}
class Menu : View {
internal MenuBarItem barItems;
MenuBar host;
internal int current;
internal View previousSubFocused;
static Rect MakeFrame (int x, int y, MenuItem [] items)
{
if (items == null || items.Length == 0) {
return new Rect ();
}
int maxW = items.Max (z => z?.Width) ?? 0;
return new Rect (x, y, maxW + 2, items.Length + 2);
}
public Menu (MenuBar host, int x, int y, MenuBarItem barItems) : base (MakeFrame (x, y, barItems.Children))
{
this.barItems = barItems;
this.host = host;
if (barItems.IsTopLevel) {
// This is a standalone MenuItem on a MenuBar
ColorScheme = Colors.Menu;
CanFocus = true;
} else {
current = -1;
for (int i = 0; i < barItems.Children.Length; i++) {
if (barItems.Children [i] != null) {
current = i;
break;
}
}
ColorScheme = Colors.Menu;
CanFocus = true;
WantMousePositionReports = host.WantMousePositionReports;
}
}
internal Attribute DetermineColorSchemeFor (MenuItem item, int index)
{
if (item != null) {
if (index == current) return ColorScheme.Focus;
if (!item.IsEnabled ()) return ColorScheme.Disabled;
}
return ColorScheme.Normal;
}
public override void Redraw (Rect region)
{
Driver.SetAttribute (ColorScheme.Normal);
DrawFrame (region, padding: 0, fill: true);
for (int i = 0; i < barItems.Children.Length; i++) {
var item = barItems.Children [i];
Driver.SetAttribute (item == null ? ColorScheme.Normal : i == current ? ColorScheme.Focus : ColorScheme.Normal);
if (item == null) {
Move (0, i + 1);
Driver.AddRune (Driver.LeftTee);
} else
Move (1, i + 1);
Driver.SetAttribute (DetermineColorSchemeFor (item, i));
for (int p = 0; p < Frame.Width - 2; p++)
if (item == null)
Driver.AddRune (Driver.HLine);
else if (p == Frame.Width - 3 && barItems.Children [i].SubMenu != null)
Driver.AddRune ('>');
else
Driver.AddRune (' ');
if (item == null) {
Move (Frame.Right - 1, i + 1);
Driver.AddRune (Driver.RightTee);
continue;
}
Move (2, i + 1);
if (!item.IsEnabled ())
DrawHotString (item.Title, ColorScheme.Disabled, ColorScheme.Disabled);
else
DrawHotString (item.Title,
i == current ? ColorScheme.HotFocus : ColorScheme.HotNormal,
i == current ? ColorScheme.Focus : ColorScheme.Normal);
// The help string
var l = item.Help.Length;
Move (Frame.Width - l - 2, 1 + i);
Driver.AddStr (item.Help);
}
PositionCursor ();
}
public override void PositionCursor ()
{
if (host == null || host.IsMenuOpen)
if (barItems.IsTopLevel) {
host.PositionCursor ();
} else
Move (2, 1 + current);
else
host.PositionCursor ();
}
public void Run (Action action)
{
if (action == null)
return;
Application.UngrabMouse ();
host.CloseAllMenus ();
Application.Refresh ();
Application.MainLoop.AddIdle (() => {
action ();
return false;
});
}
public override bool OnKeyDown (KeyEvent keyEvent)
{
if (keyEvent.IsAlt) {
host.CloseAllMenus ();
return true;
}
return false;
}
public override bool ProcessHotKey (KeyEvent keyEvent)
{
// To ncurses simulate a AltMask key pressing Alt+Space because
// it can�t detect an alone special key down was pressed.
if (keyEvent.IsAlt && keyEvent.Key == Key.AltMask) {
OnKeyDown (keyEvent);
return true;
}
return false;
}
public override bool ProcessKey (KeyEvent kb)
{
bool disabled;
switch (kb.Key) {
case Key.CursorUp:
if (barItems.IsTopLevel || current == -1)
break;
do {
disabled = false;
current--;
if (host.UseKeysUpDownAsKeysLeftRight) {
if (current == -1 && barItems.Children [current + 1].IsFromSubMenu && host.selectedSub > -1) {
current++;
host.PreviousMenu (true);
break;
}
}
if (current < 0)
current = barItems.Children.Length - 1;
var item = barItems.Children [current];
if (item == null || !item.IsEnabled ()) disabled = true;
} while (barItems.Children [current] == null || disabled);
SetNeedsDisplay ();
break;
case Key.CursorDown:
if (barItems.IsTopLevel) {
break;
}
do {
current++;
disabled = false;
if (current == barItems.Children.Length)
current = 0;
var item = barItems.Children [current];
if (item == null || !item.IsEnabled ()) disabled = true;
if (host.UseKeysUpDownAsKeysLeftRight && barItems.Children [current]?.SubMenu != null &&
!disabled && host.IsMenuOpen) {
CheckSubMenu ();
break;
}
if (!host.IsMenuOpen)
host.OpenMenu (host.selected);
} while (barItems.Children [current] == null || disabled);
SetNeedsDisplay ();
break;
case Key.CursorLeft:
host.PreviousMenu (true);
break;
case Key.CursorRight:
host.NextMenu (barItems.IsTopLevel || barItems.Children [current].IsFromSubMenu ? true : false);
break;
case Key.Esc:
Application.UngrabMouse ();
host.CloseAllMenus ();
break;
case Key.Enter:
if (barItems.IsTopLevel) {
Run (barItems.Action);
} else {
CheckSubMenu ();
Run (barItems.Children [current].Action);
}
break;
default:
// TODO: rune-ify
if (barItems.Children != null && Char.IsLetterOrDigit ((char)kb.KeyValue)) {
var x = Char.ToUpper ((char)kb.KeyValue);
foreach (var item in barItems.Children) {
if (item == null) continue;
if (item.IsEnabled () && item.HotKey == x) {
host.CloseMenu ();
Run (item.Action);
return true;
}
}
}
break;
}
return true;
}
public override bool MouseEvent (MouseEvent me)
{
if (!host.handled && !host.HandleGrabView (me, this)) {
return false;
}
host.handled = false;
bool disabled;
if (me.Flags == MouseFlags.Button1Clicked) {
disabled = false;
if (me.Y < 1)
return true;
var meY = me.Y - 1;
if (meY >= barItems.Children.Length)
return true;
var item = barItems.Children [meY];
if (item == null || !item.IsEnabled ()) disabled = true;
if (item != null && !disabled)
Run (barItems.Children [meY].Action);
return true;
} else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked ||
me.Flags == MouseFlags.ReportMousePosition ||
me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
disabled = false;
if (me.Y < 1)
return true;
if (me.Y - 1 >= barItems.Children.Length)
return true;
var item = barItems.Children [me.Y - 1];
if (item == null || !item.IsEnabled ()) disabled = true;
if (item != null && !disabled)
current = me.Y - 1;
HasFocus = true;
SetNeedsDisplay ();
CheckSubMenu ();
return true;
}
return false;
}
internal void CheckSubMenu ()
{
if (barItems.Children [current] == null)
return;
var subMenu = barItems.Children [current].SubMenu;
if (subMenu != null) {
int pos = -1;
if (host.openSubMenu != null)
pos = host.openSubMenu.FindIndex (o => o?.barItems == subMenu);
host.Activate (host.selected, pos, subMenu);
} else if (host.openSubMenu != null && !barItems.Children [current].IsFromSubMenu)
host.CloseMenu (false, true);
}
int GetSubMenuIndex (MenuBarItem subMenu)
{
int pos = -1;
if (this != null && Subviews.Count > 0) {
Menu v = null;
foreach (var menu in Subviews) {
if (((Menu)menu).barItems == subMenu)
v = (Menu)menu;
}
if (v != null)
pos = Subviews.IndexOf (v);
}
return pos;
}
}
///
/// The MenuBar provides a menu for Terminal.Gui applications.
///
///
///
/// The appears on the first row of the terminal.
///
///
/// The provides global hotkeys for the application.
///
///
public class MenuBar : View {
///
/// Gets or sets the array of s for the menu. Only set this when the is vislble.
///
/// The menu array.
public MenuBarItem [] Menus { get; set; }
internal int selected;
internal int selectedSub;
Action action;
///
/// Used for change the navigation key style.
///
public bool UseKeysUpDownAsKeysLeftRight { get; set; } = true;
///
/// Initializes a new instance of the class with the specified set of toplevel menu items.
///
/// Individual menu items; a null item will result in a separator being drawn.
public MenuBar (MenuBarItem [] menus) : base ()
{
X = 0;
Y = 0;
Width = Dim.Fill ();
Height = 1;
Menus = menus;
//CanFocus = true;
selected = -1;
selectedSub = -1;
ColorScheme = Colors.Menu;
WantMousePositionReports = true;
IsMenuOpen = false;
}
bool openedByAltKey;
///
public override bool OnKeyDown (KeyEvent keyEvent)
{
if (keyEvent.IsAlt) {
openedByAltKey = true;
SetNeedsDisplay ();
openedByHotKey = false;
}
return false;
}
///
public override bool OnKeyUp (KeyEvent keyEvent)
{
if (keyEvent.IsAlt) {
// User pressed Alt - this may be a precursor to a menu accelerator (e.g. Alt-F)
if (!keyEvent.IsCtrl && openedByAltKey && !IsMenuOpen && openMenu == null && ((uint)keyEvent.Key & (uint)Key.CharMask) == 0) {
// There's no open menu, the first menu item should be highlight.
// The right way to do this is to SetFocus(MenuBar), but for some reason
// that faults.
//Activate (0);
//StartMenu ();
IsMenuOpen = true;
selected = 0;
CanFocus = true;
lastFocused = SuperView.MostFocused;
SuperView.SetFocus (this);
SetNeedsDisplay ();
Application.GrabMouse (this);
} else if (!openedByHotKey) {
// There's an open menu. If this Alt key-up is a pre-cursor to an accelerator
// we don't want to close the menu because it'll flash.
// How to deal with that?
if (openMenu != null)
CloseAllMenus ();
openedByAltKey = false;
IsMenuOpen = false;
selected = -1;
CanFocus = false;
if (lastFocused != null)
SuperView?.SetFocus (lastFocused);
SetNeedsDisplay ();
Application.UngrabMouse ();
}
return true;
}
return false;
}
///
public override void Redraw (Rect region)
{
Move (0, 0);
Driver.SetAttribute (Colors.Menu.Normal);
for (int i = 0; i < Frame.Width; i++)
Driver.AddRune (' ');
Move (1, 0);
int pos = 1;
for (int i = 0; i < Menus.Length; i++) {
var menu = Menus [i];
Move (pos, 0);
Attribute hotColor, normalColor;
if (i == selected) {
hotColor = i == selected ? ColorScheme.HotFocus : ColorScheme.HotNormal;
normalColor = i == selected ? ColorScheme.Focus : ColorScheme.Normal;
} else if (openedByAltKey) {
hotColor = ColorScheme.HotNormal;
normalColor = ColorScheme.Normal;
} else {
hotColor = ColorScheme.Normal;
normalColor = ColorScheme.Normal;
}
DrawHotString ($" {menu.Title} ", hotColor, normalColor);
pos += 1 + menu.TitleLength + 2;
}
PositionCursor ();
}
///
public override void PositionCursor ()
{
int pos = 0;
for (int i = 0; i < Menus.Length; i++) {
if (i == selected) {
pos++;
if (IsMenuOpen)
Move (pos + 1, 0);
else
Move (pos + 1, 0);
return;
} else {
if (IsMenuOpen)
pos += 1 + Menus [i].TitleLength + 2;
else
pos += 2 + Menus [i].TitleLength + 1;
}
}
//Move (0, 0);
}
void Selected (MenuItem item)
{
// TODO: Running = false;
action = item.Action;
}
///
/// Raised as a menu is opened.
///
public event EventHandler OnOpenMenu;
///
/// Raised when a menu is closing.
///
public event EventHandler OnCloseMenu;
internal Menu openMenu;
Menu openCurrentMenu;
internal List