Menu.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  1. //
  2. // Menu.cs: application menus and submenus
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. // TODO:
  8. // Add accelerator support, but should also support chords (Shortcut in MenuItem)
  9. // Allow menus inside menus
  10. using System;
  11. using NStack;
  12. using System.Linq;
  13. using System.Collections.Generic;
  14. namespace Terminal.Gui {
  15. /// <summary>
  16. /// Specifies how a <see cref="MenuItem"/> shows selection state.
  17. /// </summary>
  18. [Flags]
  19. public enum MenuItemCheckStyle {
  20. /// <summary>
  21. /// The menu item will be shown normally, with no check indicator.
  22. /// </summary>
  23. NoCheck = 0b_0000_0000,
  24. /// <summary>
  25. /// The menu item will indicate checked/un-checked state (see <see cref="Checked"/>.
  26. /// </summary>
  27. Checked = 0b_0000_0001,
  28. /// <summary>
  29. /// The menu item is part of a menu radio group (see <see cref="Checked"/> and will indicate selected state.
  30. /// </summary>
  31. Radio = 0b_0000_0010,
  32. };
  33. /// <summary>
  34. /// A <see cref="MenuItem"/> has a title, an associated help text, and an action to execute on activation.
  35. /// </summary>
  36. public class MenuItem {
  37. ustring title;
  38. ShortcutHelper shortcutHelper;
  39. /// <summary>
  40. /// Initializes a new instance of <see cref="MenuItem"/>
  41. /// </summary>
  42. public MenuItem (Key shortcut = Key.Null) : this ("", "", null, null, null, shortcut) { }
  43. /// <summary>
  44. /// Initializes a new instance of <see cref="MenuItem"/>.
  45. /// </summary>
  46. /// <param name="title">Title for the menu item.</param>
  47. /// <param name="help">Help text to display.</param>
  48. /// <param name="action">Action to invoke when the menu item is activated.</param>
  49. /// <param name="canExecute">Function to determine if the action can currently be executed.</param>
  50. /// <param name="parent">The <see cref="Parent"/> of this menu item.</param>
  51. /// <param name="shortcut">The <see cref="Shortcut"/> keystroke combination.</param>
  52. public MenuItem (ustring title, ustring help, Action action, Func<bool> canExecute = null, MenuItem parent = null, Key shortcut = Key.Null)
  53. {
  54. Title = title ?? "";
  55. Help = help ?? "";
  56. Action = action;
  57. CanExecute = canExecute;
  58. Parent = parent;
  59. shortcutHelper = new ShortcutHelper ();
  60. if (shortcut != Key.Null) {
  61. shortcutHelper.Shortcut = shortcut;
  62. }
  63. }
  64. /// <summary>
  65. /// The HotKey is used when the menu is active, the shortcut can be triggered when the menu is not active.
  66. /// For example HotKey would be "N" when the File Menu is open (assuming there is a "_New" entry
  67. /// if the Shortcut is set to "Control-N", this would be a global hotkey that would trigger as well
  68. /// </summary>
  69. public Rune HotKey;
  70. /// <summary>
  71. /// This is the global setting that can be used as a global <see cref="ShortcutHelper.Shortcut"/> to invoke the action on the menu.
  72. /// </summary>
  73. public Key Shortcut {
  74. get => shortcutHelper.Shortcut;
  75. set {
  76. if (shortcutHelper.Shortcut != value && (ShortcutHelper.PostShortcutValidation (value) || value == Key.Null)) {
  77. shortcutHelper.Shortcut = value;
  78. }
  79. }
  80. }
  81. /// <summary>
  82. /// The keystroke combination used in the <see cref="ShortcutHelper.ShortcutTag"/> as string.
  83. /// </summary>
  84. public ustring ShortcutTag => ShortcutHelper.GetShortcutTag (shortcutHelper.Shortcut);
  85. /// <summary>
  86. /// Gets or sets the title.
  87. /// </summary>
  88. /// <value>The title.</value>
  89. public ustring Title {
  90. get { return title; }
  91. set {
  92. if (title != value) {
  93. title = value;
  94. GetHotKey ();
  95. }
  96. }
  97. }
  98. /// <summary>
  99. /// Gets or sets the help text for the menu item.
  100. /// </summary>
  101. /// <value>The help text.</value>
  102. public ustring Help { get; set; }
  103. /// <summary>
  104. /// Gets or sets the action to be invoked when the menu is triggered
  105. /// </summary>
  106. /// <value>Method to invoke.</value>
  107. public Action Action { get; set; }
  108. /// <summary>
  109. /// Gets or sets the action to be invoked if the menu can be triggered
  110. /// </summary>
  111. /// <value>Function to determine if action is ready to be executed.</value>
  112. public Func<bool> CanExecute { get; set; }
  113. /// <summary>
  114. /// Shortcut to check if the menu item is enabled
  115. /// </summary>
  116. public bool IsEnabled ()
  117. {
  118. return CanExecute == null ? true : CanExecute ();
  119. }
  120. internal int Width => Title.RuneCount + Help.RuneCount + 1 + 2 +
  121. (Checked || CheckType.HasFlag (MenuItemCheckStyle.Checked) || CheckType.HasFlag (MenuItemCheckStyle.Radio) ? 2 : 0) +
  122. (ShortcutTag.RuneCount > 0 ? ShortcutTag.RuneCount + 2 : 0);
  123. /// <summary>
  124. /// Sets or gets whether the <see cref="MenuItem"/> shows a check indicator or not. See <see cref="MenuItemCheckStyle"/>.
  125. /// </summary>
  126. public bool Checked { set; get; }
  127. /// <summary>
  128. /// Sets or gets the type selection indicator the menu item will be displayed with.
  129. /// </summary>
  130. public MenuItemCheckStyle CheckType { get; set; }
  131. /// <summary>
  132. /// Gets or sets the parent for this <see cref="MenuItem"/>.
  133. /// </summary>
  134. /// <value>The parent.</value>
  135. public MenuItem Parent { get; internal set; }
  136. /// <summary>
  137. /// Gets if this <see cref="MenuItem"/> is from a sub-menu.
  138. /// </summary>
  139. internal bool IsFromSubMenu { get { return Parent != null; } }
  140. /// <summary>
  141. /// Merely a debugging aid to see the interaction with main
  142. /// </summary>
  143. public MenuItem GetMenuItem ()
  144. {
  145. return this;
  146. }
  147. /// <summary>
  148. /// Merely a debugging aid to see the interaction with main
  149. /// </summary>
  150. public bool GetMenuBarItem ()
  151. {
  152. return IsFromSubMenu;
  153. }
  154. void GetHotKey ()
  155. {
  156. bool nextIsHot = false;
  157. foreach (var x in title) {
  158. if (x == '_') {
  159. nextIsHot = true;
  160. } else {
  161. if (nextIsHot) {
  162. HotKey = Char.ToUpper ((char)x);
  163. break;
  164. }
  165. nextIsHot = false;
  166. HotKey = default;
  167. }
  168. }
  169. }
  170. }
  171. /// <summary>
  172. /// A <see cref="MenuBarItem"/> contains <see cref="MenuBarItem"/>s or <see cref="MenuItem"/>s.
  173. /// </summary>
  174. public class MenuBarItem : MenuItem {
  175. /// <summary>
  176. /// Initializes a new <see cref="MenuBarItem"/> as a <see cref="MenuItem"/>.
  177. /// </summary>
  178. /// <param name="title">Title for the menu item.</param>
  179. /// <param name="help">Help text to display.</param>
  180. /// <param name="action">Action to invoke when the menu item is activated.</param>
  181. /// <param name="canExecute">Function to determine if the action can currently be executed.</param>
  182. /// <param name="parent">The parent <see cref="MenuItem"/> of this if exist, otherwise is null.</param>
  183. public MenuBarItem (ustring title, ustring help, Action action, Func<bool> canExecute = null, MenuItem parent = null) : base (title, help, action, canExecute, parent)
  184. {
  185. Initialize (title, null, null, true);
  186. }
  187. /// <summary>
  188. /// Initializes a new <see cref="MenuBarItem"/>.
  189. /// </summary>
  190. /// <param name="title">Title for the menu item.</param>
  191. /// <param name="children">The items in the current menu.</param>
  192. /// <param name="parent">The parent <see cref="MenuItem"/> of this if exist, otherwise is null.</param>
  193. public MenuBarItem (ustring title, MenuItem [] children, MenuItem parent = null)
  194. {
  195. Initialize (title, children, parent);
  196. }
  197. /// <summary>
  198. /// Initializes a new <see cref="MenuBarItem"/> with separate list of items.
  199. /// </summary>
  200. /// <param name="title">Title for the menu item.</param>
  201. /// <param name="children">The list of items in the current menu.</param>
  202. /// <param name="parent">The parent <see cref="MenuItem"/> of this if exist, otherwise is null.</param>
  203. public MenuBarItem (ustring title, List<MenuItem []> children, MenuItem parent = null)
  204. {
  205. Initialize (title, children, parent);
  206. }
  207. /// <summary>
  208. /// Initializes a new <see cref="MenuBarItem"/>.
  209. /// </summary>
  210. /// <param name="children">The items in the current menu.</param>
  211. public MenuBarItem (MenuItem [] children) : this ("", children) { }
  212. /// <summary>
  213. /// Initializes a new <see cref="MenuBarItem"/>.
  214. /// </summary>
  215. public MenuBarItem () : this (children: new MenuItem [] { }) { }
  216. void Initialize (ustring title, object children, MenuItem parent = null, bool isTopLevel = false)
  217. {
  218. if (!isTopLevel && children == null) {
  219. throw new ArgumentNullException (nameof (children), "The parameter cannot be null. Use an empty array instead.");
  220. }
  221. SetTitle (title ?? "");
  222. if (parent != null) {
  223. Parent = parent;
  224. }
  225. if (children is List<MenuItem []>) {
  226. MenuItem [] childrens = new MenuItem [] { };
  227. foreach (var item in (List<MenuItem []>)children) {
  228. for (int i = 0; i < item.Length; i++) {
  229. SetChildrensParent (item);
  230. Array.Resize (ref childrens, childrens.Length + 1);
  231. childrens [childrens.Length - 1] = item [i];
  232. }
  233. }
  234. Children = childrens;
  235. } else if (children is MenuItem []) {
  236. SetChildrensParent ((MenuItem [])children);
  237. Children = (MenuItem [])children;
  238. } else {
  239. Children = null;
  240. }
  241. }
  242. //static int GetMaxTitleLength (MenuItem [] children)
  243. //{
  244. // int maxLength = 0;
  245. // foreach (var item in children) {
  246. // int len = GetMenuBarItemLength (item.Title);
  247. // if (len > maxLength)
  248. // maxLength = len;
  249. // item.IsFromSubMenu = true;
  250. // }
  251. // return maxLength;
  252. //}
  253. void SetChildrensParent (MenuItem [] childrens)
  254. {
  255. foreach (var child in childrens) {
  256. if (child != null && child.Parent == null) {
  257. child.Parent = this;
  258. }
  259. }
  260. }
  261. /// <summary>
  262. /// Check if the children parameter is a <see cref="MenuBarItem"/>.
  263. /// </summary>
  264. /// <param name="children"></param>
  265. /// <returns>Returns a <see cref="MenuBarItem"/> or null otherwise.</returns>
  266. public MenuBarItem SubMenu (MenuItem children)
  267. {
  268. return children as MenuBarItem;
  269. }
  270. /// <summary>
  271. /// Check if the <see cref="MenuItem"/> parameter is a child of this.
  272. /// </summary>
  273. /// <param name="menuItem"></param>
  274. /// <returns>Returns <c>true</c> if it is a child of this. <c>false</c> otherwise.</returns>
  275. public bool IsSubMenuOf (MenuItem menuItem)
  276. {
  277. foreach (var child in Children) {
  278. if (child == menuItem && child.Parent == menuItem.Parent) {
  279. return true;
  280. }
  281. }
  282. return false;
  283. }
  284. /// <summary>
  285. /// Get the index of the <see cref="MenuItem"/> parameter.
  286. /// </summary>
  287. /// <param name="children"></param>
  288. /// <returns>Returns a value bigger than -1 if the <see cref="MenuItem"/> is a child of this.</returns>
  289. public int GetChildrenIndex (MenuItem children)
  290. {
  291. if (Children?.Length == 0) {
  292. return -1;
  293. }
  294. int i = 0;
  295. foreach (var child in Children) {
  296. if (child == children) {
  297. return i;
  298. }
  299. i++;
  300. }
  301. return -1;
  302. }
  303. void SetTitle (ustring title)
  304. {
  305. if (title == null)
  306. title = "";
  307. Title = title;
  308. }
  309. int GetMenuBarItemLength (ustring title)
  310. {
  311. int len = 0;
  312. foreach (var ch in title) {
  313. if (ch == '_')
  314. continue;
  315. len++;
  316. }
  317. return len;
  318. }
  319. ///// <summary>
  320. ///// Gets or sets the title to display.
  321. ///// </summary>
  322. ///// <value>The title.</value>
  323. //public ustring Title { get; set; }
  324. /// <summary>
  325. /// Gets or sets an array of <see cref="MenuItem"/> objects that are the children of this <see cref="MenuBarItem"/>
  326. /// </summary>
  327. /// <value>The children.</value>
  328. public MenuItem [] Children { get; set; }
  329. internal int TitleLength => GetMenuBarItemLength (Title);
  330. internal bool IsTopLevel { get => Parent == null && (Children == null || Children.Length == 0) && Action != null; }
  331. }
  332. class Menu : View {
  333. internal MenuBarItem barItems;
  334. MenuBar host;
  335. internal int current;
  336. internal View previousSubFocused;
  337. static Rect MakeFrame (int x, int y, MenuItem [] items)
  338. {
  339. if (items == null || items.Length == 0) {
  340. return new Rect ();
  341. }
  342. int maxW = items.Max (z => z?.Width) ?? 0;
  343. return new Rect (x, y, maxW + 2, items.Length + 2);
  344. }
  345. public Menu (MenuBar host, int x, int y, MenuBarItem barItems) : base (MakeFrame (x, y, barItems.Children))
  346. {
  347. this.barItems = barItems;
  348. this.host = host;
  349. if (barItems.IsTopLevel) {
  350. // This is a standalone MenuItem on a MenuBar
  351. ColorScheme = host.ColorScheme;
  352. CanFocus = true;
  353. } else {
  354. current = -1;
  355. for (int i = 0; i < barItems.Children?.Length; i++) {
  356. if (barItems.Children [i] != null) {
  357. current = i;
  358. break;
  359. }
  360. }
  361. ColorScheme = host.ColorScheme;
  362. CanFocus = true;
  363. WantMousePositionReports = host.WantMousePositionReports;
  364. }
  365. }
  366. internal Attribute DetermineColorSchemeFor (MenuItem item, int index)
  367. {
  368. if (item != null) {
  369. if (index == current) return ColorScheme.Focus;
  370. if (!item.IsEnabled ()) return ColorScheme.Disabled;
  371. }
  372. return GetNormalColor ();
  373. }
  374. public override void Redraw (Rect bounds)
  375. {
  376. Driver.SetAttribute (GetNormalColor ());
  377. DrawFrame (bounds, padding: 0, fill: true);
  378. for (int i = 0; i < barItems.Children.Length; i++) {
  379. var item = barItems.Children [i];
  380. Driver.SetAttribute (item == null ? GetNormalColor ()
  381. : i == current ? ColorScheme.Focus : GetNormalColor ());
  382. if (item == null) {
  383. Move (0, i + 1);
  384. Driver.AddRune (Driver.LeftTee);
  385. } else
  386. Move (1, i + 1);
  387. Driver.SetAttribute (DetermineColorSchemeFor (item, i));
  388. for (int p = 0; p < Frame.Width - 2; p++)
  389. if (item == null)
  390. Driver.AddRune (Driver.HLine);
  391. else if (p == Frame.Width - 3 && barItems.SubMenu (barItems.Children [i]) != null)
  392. Driver.AddRune (Driver.RightArrow);
  393. else
  394. Driver.AddRune (' ');
  395. if (item == null) {
  396. Move (Frame.Width - 1, i + 1);
  397. Driver.AddRune (Driver.RightTee);
  398. continue;
  399. }
  400. ustring textToDraw;
  401. var checkChar = Driver.Selected;
  402. var uncheckedChar = Driver.UnSelected;
  403. if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked)) {
  404. checkChar = Driver.Checked;
  405. uncheckedChar = Driver.UnChecked;
  406. }
  407. // Support Checked even though CheckType wasn't set
  408. if (item.Checked) {
  409. textToDraw = ustring.Make (new Rune [] { checkChar, ' ' }) + item.Title;
  410. } else if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked) || item.CheckType.HasFlag (MenuItemCheckStyle.Radio)) {
  411. textToDraw = ustring.Make (new Rune [] { uncheckedChar, ' ' }) + item.Title;
  412. } else {
  413. textToDraw = item.Title;
  414. }
  415. Move (2, i + 1);
  416. if (!item.IsEnabled ())
  417. DrawHotString (textToDraw, ColorScheme.Disabled, ColorScheme.Disabled);
  418. else
  419. DrawHotString (textToDraw,
  420. i == current ? ColorScheme.HotFocus : ColorScheme.HotNormal,
  421. i == current ? ColorScheme.Focus : GetNormalColor ());
  422. // The help string
  423. var l = item.ShortcutTag.RuneCount == 0 ? item.Help.RuneCount : item.Help.RuneCount + item.ShortcutTag.RuneCount + 2;
  424. Move (Frame.Width - l - 2, 1 + i);
  425. Driver.AddStr (item.Help);
  426. // The shortcut tag string
  427. if (!item.ShortcutTag.IsEmpty) {
  428. l = item.ShortcutTag.RuneCount;
  429. Move (Frame.Width - l - 2, 1 + i);
  430. Driver.AddStr (item.ShortcutTag);
  431. }
  432. }
  433. PositionCursor ();
  434. }
  435. public override void PositionCursor ()
  436. {
  437. if (host == null || host.IsMenuOpen)
  438. if (barItems.IsTopLevel) {
  439. host.PositionCursor ();
  440. } else
  441. Move (2, 1 + current);
  442. else
  443. host.PositionCursor ();
  444. }
  445. public void Run (Action action)
  446. {
  447. if (action == null)
  448. return;
  449. Application.UngrabMouse ();
  450. host.CloseAllMenus ();
  451. Application.Refresh ();
  452. Application.MainLoop.AddIdle (() => {
  453. action ();
  454. return false;
  455. });
  456. }
  457. public override bool OnLeave (View view)
  458. {
  459. return host.OnLeave (view);
  460. }
  461. public override bool OnKeyDown (KeyEvent keyEvent)
  462. {
  463. if (keyEvent.IsAlt) {
  464. host.CloseAllMenus ();
  465. return true;
  466. }
  467. return false;
  468. }
  469. public override bool ProcessHotKey (KeyEvent keyEvent)
  470. {
  471. // To ncurses simulate a AltMask key pressing Alt+Space because
  472. // it can�t detect an alone special key down was pressed.
  473. if (keyEvent.IsAlt && keyEvent.Key == Key.AltMask) {
  474. OnKeyDown (keyEvent);
  475. return true;
  476. }
  477. return false;
  478. }
  479. public override bool ProcessKey (KeyEvent kb)
  480. {
  481. switch (kb.Key) {
  482. case Key.Tab:
  483. host.CleanUp ();
  484. return true;
  485. case Key.CursorUp:
  486. return MoveUp ();
  487. case Key.CursorDown:
  488. return MoveDown ();
  489. case Key.CursorLeft:
  490. host.PreviousMenu (true);
  491. return true;
  492. case Key.CursorRight:
  493. host.NextMenu (barItems.IsTopLevel || (barItems.Children != null && current > -1 && current < barItems.Children.Length && barItems.Children [current].IsFromSubMenu) ? true : false);
  494. return true;
  495. case Key.Esc:
  496. CloseAllMenus ();
  497. return true;
  498. case Key.Enter:
  499. RunSelected ();
  500. return true;
  501. default:
  502. // TODO: rune-ify
  503. if (barItems.Children != null && Char.IsLetterOrDigit ((char)kb.KeyValue)) {
  504. var x = Char.ToUpper ((char)kb.KeyValue);
  505. foreach (var item in barItems.Children) {
  506. if (item == null) continue;
  507. if (item.IsEnabled () && item.HotKey == x) {
  508. host.CloseMenu ();
  509. Run (item.Action);
  510. return true;
  511. }
  512. }
  513. }
  514. break;
  515. }
  516. return false;
  517. }
  518. void RunSelected ()
  519. {
  520. if (barItems.IsTopLevel) {
  521. Run (barItems.Action);
  522. } else if (current > -1) {
  523. Run (barItems.Children [current].Action);
  524. }
  525. }
  526. void CloseAllMenus ()
  527. {
  528. Application.UngrabMouse ();
  529. host.CloseAllMenus ();
  530. }
  531. bool MoveDown ()
  532. {
  533. if (barItems.IsTopLevel) {
  534. return true;
  535. }
  536. bool disabled;
  537. do {
  538. current++;
  539. if (current >= barItems.Children.Length) {
  540. current = 0;
  541. }
  542. if (this != host.openCurrentMenu && barItems.Children [current].IsFromSubMenu && host.selectedSub > -1) {
  543. host.PreviousMenu (true);
  544. host.SelectEnabledItem (barItems.Children, current, out current);
  545. host.openCurrentMenu = this;
  546. }
  547. var item = barItems.Children [current];
  548. if (item?.IsEnabled () != true) {
  549. disabled = true;
  550. } else {
  551. disabled = false;
  552. }
  553. if (host.UseKeysUpDownAsKeysLeftRight && barItems.SubMenu (barItems.Children [current]) != null &&
  554. !disabled && host.IsMenuOpen) {
  555. CheckSubMenu ();
  556. break;
  557. }
  558. if (!host.IsMenuOpen) {
  559. host.OpenMenu (host.selected);
  560. }
  561. } while (barItems.Children [current] == null || disabled);
  562. SetNeedsDisplay ();
  563. host.OnMenuOpened ();
  564. return true;
  565. }
  566. bool MoveUp ()
  567. {
  568. if (barItems.IsTopLevel || current == -1) {
  569. return true;
  570. }
  571. bool disabled;
  572. do {
  573. current--;
  574. if (host.UseKeysUpDownAsKeysLeftRight) {
  575. if ((current == -1 || this != host.openCurrentMenu) && barItems.Children [current + 1].IsFromSubMenu && host.selectedSub > -1) {
  576. current++;
  577. host.PreviousMenu (true);
  578. if (current > 0) {
  579. current--;
  580. host.openCurrentMenu = this;
  581. }
  582. break;
  583. }
  584. }
  585. if (current < 0)
  586. current = barItems.Children.Length - 1;
  587. if (!host.SelectEnabledItem (barItems.Children, current, out current, false)) {
  588. current = 0;
  589. if (!host.SelectEnabledItem (barItems.Children, current, out current)) {
  590. host.CloseMenu ();
  591. }
  592. break;
  593. }
  594. var item = barItems.Children [current];
  595. if (item?.IsEnabled () != true) {
  596. disabled = true;
  597. } else {
  598. disabled = false;
  599. }
  600. if (host.UseKeysUpDownAsKeysLeftRight && barItems.SubMenu (barItems.Children [current]) != null &&
  601. !disabled && host.IsMenuOpen) {
  602. CheckSubMenu ();
  603. break;
  604. }
  605. } while (barItems.Children [current] == null || disabled);
  606. SetNeedsDisplay ();
  607. host.OnMenuOpened ();
  608. return true;
  609. }
  610. public override bool MouseEvent (MouseEvent me)
  611. {
  612. if (!host.handled && !host.HandleGrabView (me, this)) {
  613. return false;
  614. }
  615. host.handled = false;
  616. bool disabled;
  617. if (me.Flags == MouseFlags.Button1Clicked) {
  618. disabled = false;
  619. if (me.Y < 1)
  620. return true;
  621. var meY = me.Y - 1;
  622. if (meY >= barItems.Children.Length)
  623. return true;
  624. var item = barItems.Children [meY];
  625. if (item == null || !item.IsEnabled ()) disabled = true;
  626. if (item != null && !disabled)
  627. Run (barItems.Children [meY].Action);
  628. return true;
  629. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked ||
  630. me.Flags == MouseFlags.Button1TripleClicked || me.Flags == MouseFlags.ReportMousePosition ||
  631. me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  632. disabled = false;
  633. if (me.Y < 1 || me.Y - 1 >= barItems.Children.Length) {
  634. return true;
  635. }
  636. var item = barItems.Children [me.Y - 1];
  637. if (item == null || !item.IsEnabled ()) disabled = true;
  638. if (item != null && !disabled)
  639. current = me.Y - 1;
  640. CheckSubMenu ();
  641. host.OnMenuOpened ();
  642. return true;
  643. }
  644. return false;
  645. }
  646. internal void CheckSubMenu ()
  647. {
  648. if (current == -1 || barItems.Children [current] == null) {
  649. return;
  650. }
  651. var subMenu = barItems.SubMenu (barItems.Children [current]);
  652. if (subMenu != null) {
  653. int pos = -1;
  654. if (host.openSubMenu != null) {
  655. pos = host.openSubMenu.FindIndex (o => o?.barItems == subMenu);
  656. }
  657. if (pos == -1 && this != host.openCurrentMenu && subMenu.Children != host.openCurrentMenu.barItems.Children) {
  658. host.CloseMenu (false, true);
  659. }
  660. host.Activate (host.selected, pos, subMenu);
  661. } else if (host.openSubMenu?.Last ().barItems.IsSubMenuOf (barItems.Children [current]) == false) {
  662. host.CloseMenu (false, true);
  663. } else {
  664. SetNeedsDisplay ();
  665. }
  666. }
  667. int GetSubMenuIndex (MenuBarItem subMenu)
  668. {
  669. int pos = -1;
  670. if (this != null && Subviews.Count > 0) {
  671. Menu v = null;
  672. foreach (var menu in Subviews) {
  673. if (((Menu)menu).barItems == subMenu)
  674. v = (Menu)menu;
  675. }
  676. if (v != null)
  677. pos = Subviews.IndexOf (v);
  678. }
  679. return pos;
  680. }
  681. ///<inheritdoc/>
  682. public override bool OnEnter (View view)
  683. {
  684. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  685. return base.OnEnter (view);
  686. }
  687. }
  688. /// <summary>
  689. /// The MenuBar provides a menu for Terminal.Gui applications.
  690. /// </summary>
  691. /// <remarks>
  692. /// <para>
  693. /// The <see cref="MenuBar"/> appears on the first row of the terminal.
  694. /// </para>
  695. /// <para>
  696. /// The <see cref="MenuBar"/> provides global hotkeys for the application.
  697. /// </para>
  698. /// </remarks>
  699. public class MenuBar : View {
  700. /// <summary>
  701. /// Gets or sets the array of <see cref="MenuBarItem"/>s for the menu. Only set this when the <see cref="MenuBar"/> is vislble.
  702. /// </summary>
  703. /// <value>The menu array.</value>
  704. public MenuBarItem [] Menus { get; set; }
  705. internal int selected;
  706. internal int selectedSub;
  707. Action action;
  708. /// <summary>
  709. /// Used for change the navigation key style.
  710. /// </summary>
  711. public bool UseKeysUpDownAsKeysLeftRight { get; set; } = true;
  712. static ustring shortcutDelimiter = "+";
  713. /// <summary>
  714. /// Used for change the shortcut delimiter separator.
  715. /// </summary>
  716. public static ustring ShortcutDelimiter {
  717. get => shortcutDelimiter;
  718. set {
  719. if (shortcutDelimiter != value) {
  720. shortcutDelimiter = value == ustring.Empty ? " " : value;
  721. }
  722. }
  723. }
  724. /// <summary>
  725. /// Initializes a new instance of the <see cref="MenuBar"/>.
  726. /// </summary>
  727. public MenuBar () : this (new MenuBarItem [] { }) { }
  728. /// <summary>
  729. /// Initializes a new instance of the <see cref="MenuBar"/> class with the specified set of toplevel menu items.
  730. /// </summary>
  731. /// <param name="menus">Individual menu items; a null item will result in a separator being drawn.</param>
  732. public MenuBar (MenuBarItem [] menus) : base ()
  733. {
  734. X = 0;
  735. Y = 0;
  736. Width = Dim.Fill ();
  737. Height = 1;
  738. Menus = menus;
  739. //CanFocus = true;
  740. selected = -1;
  741. selectedSub = -1;
  742. ColorScheme = Colors.Menu;
  743. WantMousePositionReports = true;
  744. IsMenuOpen = false;
  745. }
  746. bool openedByAltKey;
  747. bool isCleaning;
  748. ///<inheritdoc/>
  749. public override bool OnLeave (View view)
  750. {
  751. if ((!(view is MenuBar) && !(view is Menu) || !(view is MenuBar) && !(view is Menu) && openMenu != null) && !isCleaning && !reopen) {
  752. CleanUp ();
  753. return true;
  754. }
  755. return false;
  756. }
  757. ///<inheritdoc/>
  758. public override bool OnKeyDown (KeyEvent keyEvent)
  759. {
  760. if (keyEvent.IsAlt || (keyEvent.IsCtrl && keyEvent.Key == (Key.CtrlMask | Key.Space))) {
  761. openedByAltKey = true;
  762. SetNeedsDisplay ();
  763. openedByHotKey = false;
  764. }
  765. return false;
  766. }
  767. ///<inheritdoc/>
  768. public override bool OnKeyUp (KeyEvent keyEvent)
  769. {
  770. if (keyEvent.IsAlt || (keyEvent.IsCtrl && keyEvent.Key == (Key.CtrlMask | Key.Space))) {
  771. // User pressed Alt - this may be a precursor to a menu accelerator (e.g. Alt-F)
  772. if (openedByAltKey && !IsMenuOpen && openMenu == null && (((uint)keyEvent.Key & (uint)Key.CharMask) == 0
  773. || ((uint)keyEvent.Key & (uint)Key.CharMask) == (uint)Key.Space)) {
  774. // There's no open menu, the first menu item should be highlight.
  775. // The right way to do this is to SetFocus(MenuBar), but for some reason
  776. // that faults.
  777. //Activate (0);
  778. //StartMenu ();
  779. IsMenuOpen = true;
  780. selected = 0;
  781. CanFocus = true;
  782. lastFocused = SuperView.MostFocused;
  783. SetFocus ();
  784. SetNeedsDisplay ();
  785. Application.GrabMouse (this);
  786. } else if (!openedByHotKey) {
  787. // There's an open menu. If this Alt key-up is a pre-cursor to an accelerator
  788. // we don't want to close the menu because it'll flash.
  789. // How to deal with that?
  790. CleanUp ();
  791. }
  792. return true;
  793. }
  794. return false;
  795. }
  796. internal void CleanUp ()
  797. {
  798. isCleaning = true;
  799. if (openMenu != null) {
  800. CloseAllMenus ();
  801. }
  802. openedByAltKey = false;
  803. IsMenuOpen = false;
  804. selected = -1;
  805. CanFocus = false;
  806. if (lastFocused != null) {
  807. lastFocused.SetFocus ();
  808. }
  809. SetNeedsDisplay ();
  810. Application.UngrabMouse ();
  811. isCleaning = false;
  812. }
  813. ///<inheritdoc/>
  814. public override void Redraw (Rect bounds)
  815. {
  816. Move (0, 0);
  817. Driver.SetAttribute (GetNormalColor ());
  818. for (int i = 0; i < Frame.Width; i++)
  819. Driver.AddRune (' ');
  820. Move (1, 0);
  821. int pos = 1;
  822. for (int i = 0; i < Menus.Length; i++) {
  823. var menu = Menus [i];
  824. Move (pos, 0);
  825. Attribute hotColor, normalColor;
  826. if (i == selected && IsMenuOpen) {
  827. hotColor = i == selected ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  828. normalColor = i == selected ? ColorScheme.Focus :
  829. GetNormalColor ();
  830. } else if (openedByAltKey) {
  831. hotColor = ColorScheme.HotNormal;
  832. normalColor = GetNormalColor ();
  833. } else {
  834. hotColor = GetNormalColor ();
  835. normalColor = GetNormalColor ();
  836. }
  837. DrawHotString (menu.Help.IsEmpty ? $" {menu.Title} " : $" {menu.Title} {menu.Help} ", hotColor, normalColor);
  838. pos += 1 + menu.TitleLength + (menu.Help.Length > 0 ? menu.Help.Length + 2 : 0) + 2;
  839. }
  840. PositionCursor ();
  841. }
  842. ///<inheritdoc/>
  843. public override void PositionCursor ()
  844. {
  845. if (selected == -1 && HasFocus && Menus.Length > 0) {
  846. selected = 0;
  847. }
  848. int pos = 0;
  849. for (int i = 0; i < Menus.Length; i++) {
  850. if (i == selected) {
  851. pos++;
  852. if (IsMenuOpen)
  853. Move (pos + 1, 0);
  854. else {
  855. Move (pos + 1, 0);
  856. }
  857. return;
  858. } else if (IsMenuOpen) {
  859. pos += 1 + Menus [i].TitleLength + (Menus [i].Help.Length > 0 ? Menus [i].Help.Length + 2 : 0) + 2;
  860. } else {
  861. pos += 2 + Menus [i].TitleLength + (Menus [i].Help.Length > 0 ? Menus [i].Help.Length + 2 : 0) + 1;
  862. }
  863. }
  864. //Move (0, 0);
  865. }
  866. void Selected (MenuItem item)
  867. {
  868. // TODO: Running = false;
  869. action = item.Action;
  870. }
  871. /// <summary>
  872. /// Raised as a menu is opening.
  873. /// </summary>
  874. public event Action<MenuOpeningEventArgs> MenuOpening;
  875. /// <summary>
  876. /// Raised when a menu is opened.
  877. /// </summary>
  878. public event Action<MenuItem> MenuOpened;
  879. /// <summary>
  880. /// Raised when a menu is closing.
  881. /// </summary>
  882. public event Action MenuClosing;
  883. internal Menu openMenu;
  884. Menu ocm;
  885. internal Menu openCurrentMenu {
  886. get => ocm;
  887. set {
  888. if (ocm != value) {
  889. ocm = value;
  890. OnMenuOpened ();
  891. }
  892. }
  893. }
  894. internal List<Menu> openSubMenu;
  895. View previousFocused;
  896. internal bool isMenuOpening;
  897. internal bool isMenuClosing;
  898. /// <summary>
  899. /// True if the menu is open; otherwise false.
  900. /// </summary>
  901. public bool IsMenuOpen { get; protected set; }
  902. /// <summary>
  903. /// Virtual method that will invoke the <see cref="MenuOpening"/> event if it's defined.
  904. /// </summary>
  905. /// <param name="currentMenu">The current menu to be replaced.</param>
  906. /// <returns>Returns the <see cref="MenuOpeningEventArgs"/></returns>
  907. public virtual MenuOpeningEventArgs OnMenuOpening (MenuBarItem currentMenu)
  908. {
  909. var ev = new MenuOpeningEventArgs (currentMenu);
  910. MenuOpening?.Invoke (ev);
  911. return ev;
  912. }
  913. /// <summary>
  914. /// Virtual method that will invoke the <see cref="MenuOpened"/> event if it's defined.
  915. /// </summary>
  916. public virtual void OnMenuOpened ()
  917. {
  918. MenuItem mi = null;
  919. if (openCurrentMenu.barItems.Children != null) {
  920. mi = openCurrentMenu.barItems.Children [openCurrentMenu.current];
  921. }
  922. MenuOpened?.Invoke (mi);
  923. }
  924. /// <summary>
  925. /// Virtual method that will invoke the <see cref="MenuClosing"/>
  926. /// </summary>
  927. public virtual void OnMenuClosing ()
  928. {
  929. MenuClosing?.Invoke ();
  930. }
  931. View lastFocused;
  932. /// <summary>
  933. /// Get the lasted focused view before open the menu.
  934. /// </summary>
  935. public View LastFocused { get; private set; }
  936. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem subMenu = null)
  937. {
  938. isMenuOpening = true;
  939. var newMenu = OnMenuOpening (Menus [index]);
  940. if (newMenu.Cancel) {
  941. return;
  942. }
  943. if (newMenu.NewMenuBarItem != null) {
  944. Menus [index] = newMenu.NewMenuBarItem;
  945. }
  946. int pos = 0;
  947. switch (subMenu) {
  948. case null:
  949. lastFocused = lastFocused ?? SuperView?.MostFocused;
  950. if (openSubMenu != null)
  951. CloseMenu (false, true);
  952. if (openMenu != null) {
  953. SuperView.Remove (openMenu);
  954. openMenu.Dispose ();
  955. }
  956. for (int i = 0; i < index; i++)
  957. pos += Menus [i].Title.RuneCount + (Menus [i].Help.RuneCount > 0 ? Menus [i].Help.RuneCount + 2 : 0) + 2;
  958. openMenu = new Menu (this, pos, 1, Menus [index]);
  959. openCurrentMenu = openMenu;
  960. openCurrentMenu.previousSubFocused = openMenu;
  961. SuperView.Add (openMenu);
  962. openMenu.SetFocus ();
  963. break;
  964. default:
  965. if (openSubMenu == null)
  966. openSubMenu = new List<Menu> ();
  967. if (sIndex > -1) {
  968. RemoveSubMenu (sIndex);
  969. } else {
  970. var last = openSubMenu.Count > 0 ? openSubMenu.Last () : openMenu;
  971. openCurrentMenu = new Menu (this, last.Frame.Left + last.Frame.Width, last.Frame.Top + 1 + last.current, subMenu);
  972. openCurrentMenu.previousSubFocused = last.previousSubFocused;
  973. openSubMenu.Add (openCurrentMenu);
  974. SuperView.Add (openCurrentMenu);
  975. }
  976. selectedSub = openSubMenu.Count - 1;
  977. if (selectedSub > -1 && SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  978. openCurrentMenu.SetFocus ();
  979. }
  980. break;
  981. }
  982. isMenuOpening = false;
  983. IsMenuOpen = true;
  984. }
  985. /// <summary>
  986. /// Opens the current Menu programatically.
  987. /// </summary>
  988. public void OpenMenu ()
  989. {
  990. if (openMenu != null)
  991. return;
  992. selected = 0;
  993. SetNeedsDisplay ();
  994. previousFocused = SuperView.Focused;
  995. OpenMenu (selected);
  996. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  997. CloseMenu ();
  998. }
  999. openCurrentMenu.CheckSubMenu ();
  1000. Application.GrabMouse (this);
  1001. }
  1002. // Activates the menu, handles either first focus, or activating an entry when it was already active
  1003. // For mouse events.
  1004. internal void Activate (int idx, int sIdx = -1, MenuBarItem subMenu = null)
  1005. {
  1006. selected = idx;
  1007. selectedSub = sIdx;
  1008. if (openMenu == null)
  1009. previousFocused = SuperView.Focused;
  1010. OpenMenu (idx, sIdx, subMenu);
  1011. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  1012. if (subMenu == null) {
  1013. CloseMenu ();
  1014. }
  1015. }
  1016. SetNeedsDisplay ();
  1017. }
  1018. internal bool SelectEnabledItem (IEnumerable<MenuItem> chldren, int current, out int newCurrent, bool forward = true)
  1019. {
  1020. if (chldren == null) {
  1021. newCurrent = -1;
  1022. return true;
  1023. }
  1024. IEnumerable<MenuItem> childrens;
  1025. if (forward) {
  1026. childrens = chldren;
  1027. } else {
  1028. childrens = chldren.Reverse ();
  1029. }
  1030. int count;
  1031. if (forward) {
  1032. count = -1;
  1033. } else {
  1034. count = childrens.Count ();
  1035. }
  1036. foreach (var child in childrens) {
  1037. if (forward) {
  1038. if (++count < current) {
  1039. continue;
  1040. }
  1041. } else {
  1042. if (--count > current) {
  1043. continue;
  1044. }
  1045. }
  1046. if (child == null || !child.IsEnabled ()) {
  1047. if (forward) {
  1048. current++;
  1049. } else {
  1050. current--;
  1051. }
  1052. } else {
  1053. newCurrent = current;
  1054. return true;
  1055. }
  1056. }
  1057. newCurrent = -1;
  1058. return false;
  1059. }
  1060. /// <summary>
  1061. /// Closes the current Menu programatically, if open.
  1062. /// </summary>
  1063. public void CloseMenu ()
  1064. {
  1065. CloseMenu (false, false);
  1066. }
  1067. bool reopen;
  1068. internal void CloseMenu (bool reopen = false, bool isSubMenu = false)
  1069. {
  1070. isMenuClosing = true;
  1071. this.reopen = reopen;
  1072. OnMenuClosing ();
  1073. switch (isSubMenu) {
  1074. case false:
  1075. if (openMenu != null) {
  1076. SuperView?.Remove (openMenu);
  1077. }
  1078. SetNeedsDisplay ();
  1079. if (previousFocused != null && previousFocused is Menu && openMenu != null && previousFocused.ToString () != openCurrentMenu.ToString ())
  1080. previousFocused.SetFocus ();
  1081. openMenu?.Dispose ();
  1082. openMenu = null;
  1083. if (lastFocused is Menu || lastFocused is MenuBar) {
  1084. lastFocused = null;
  1085. }
  1086. LastFocused = lastFocused;
  1087. lastFocused = null;
  1088. if (LastFocused != null && LastFocused.CanFocus) {
  1089. if (!reopen) {
  1090. selected = -1;
  1091. }
  1092. LastFocused.SetFocus ();
  1093. } else {
  1094. SetFocus ();
  1095. PositionCursor ();
  1096. }
  1097. IsMenuOpen = false;
  1098. break;
  1099. case true:
  1100. selectedSub = -1;
  1101. SetNeedsDisplay ();
  1102. RemoveAllOpensSubMenus ();
  1103. openCurrentMenu.previousSubFocused.SetFocus ();
  1104. openSubMenu = null;
  1105. IsMenuOpen = true;
  1106. break;
  1107. }
  1108. this.reopen = false;
  1109. isMenuClosing = false;
  1110. }
  1111. void RemoveSubMenu (int index)
  1112. {
  1113. if (openSubMenu == null)
  1114. return;
  1115. for (int i = openSubMenu.Count - 1; i > index; i--) {
  1116. isMenuClosing = true;
  1117. Menu menu;
  1118. if (openSubMenu.Count - 1 > 0)
  1119. menu = openSubMenu [i - 1];
  1120. else
  1121. menu = openMenu;
  1122. openCurrentMenu = menu;
  1123. openCurrentMenu.SetFocus ();
  1124. if (openSubMenu != null) {
  1125. menu = openSubMenu [i];
  1126. SuperView.Remove (menu);
  1127. openSubMenu.Remove (menu);
  1128. menu.Dispose ();
  1129. }
  1130. RemoveSubMenu (i);
  1131. }
  1132. if (openSubMenu.Count > 0)
  1133. openCurrentMenu = openSubMenu.Last ();
  1134. //if (openMenu.Subviews.Count == 0)
  1135. // return;
  1136. //if (index == 0) {
  1137. // //SuperView.SetFocus (previousSubFocused);
  1138. // FocusPrev ();
  1139. // return;
  1140. //}
  1141. //for (int i = openMenu.Subviews.Count - 1; i > index; i--) {
  1142. // isMenuClosing = true;
  1143. // if (openMenu.Subviews.Count - 1 > 0)
  1144. // SuperView.SetFocus (openMenu.Subviews [i - 1]);
  1145. // else
  1146. // SuperView.SetFocus (openMenu);
  1147. // if (openMenu != null) {
  1148. // Remove (openMenu.Subviews [i]);
  1149. // openMenu.Remove (openMenu.Subviews [i]);
  1150. // }
  1151. // RemoveSubMenu (i);
  1152. //}
  1153. isMenuClosing = false;
  1154. }
  1155. internal void RemoveAllOpensSubMenus ()
  1156. {
  1157. if (openSubMenu != null) {
  1158. foreach (var item in openSubMenu) {
  1159. SuperView.Remove (item);
  1160. item.Dispose ();
  1161. }
  1162. }
  1163. }
  1164. internal void CloseAllMenus ()
  1165. {
  1166. if (!isMenuOpening && !isMenuClosing) {
  1167. if (openSubMenu != null)
  1168. CloseMenu (false, true);
  1169. CloseMenu ();
  1170. if (LastFocused != null && LastFocused != this)
  1171. selected = -1;
  1172. }
  1173. IsMenuOpen = false;
  1174. openedByHotKey = false;
  1175. openedByAltKey = false;
  1176. }
  1177. View FindDeepestMenu (View view, ref int count)
  1178. {
  1179. count = count > 0 ? count : 0;
  1180. foreach (var menu in view.Subviews) {
  1181. if (menu is Menu) {
  1182. count++;
  1183. return FindDeepestMenu ((Menu)menu, ref count);
  1184. }
  1185. }
  1186. return view;
  1187. }
  1188. internal void PreviousMenu (bool isSubMenu = false)
  1189. {
  1190. switch (isSubMenu) {
  1191. case false:
  1192. if (selected <= 0)
  1193. selected = Menus.Length - 1;
  1194. else
  1195. selected--;
  1196. if (selected > -1)
  1197. CloseMenu (true, false);
  1198. OpenMenu (selected);
  1199. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current, false)) {
  1200. openCurrentMenu.current = 0;
  1201. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  1202. CloseMenu ();
  1203. }
  1204. break;
  1205. }
  1206. break;
  1207. case true:
  1208. if (selectedSub > -1) {
  1209. selectedSub--;
  1210. RemoveSubMenu (selectedSub);
  1211. SetNeedsDisplay ();
  1212. } else
  1213. PreviousMenu ();
  1214. break;
  1215. }
  1216. }
  1217. internal void NextMenu (bool isSubMenu = false)
  1218. {
  1219. switch (isSubMenu) {
  1220. case false:
  1221. if (selected == -1)
  1222. selected = 0;
  1223. else if (selected + 1 == Menus.Length)
  1224. selected = 0;
  1225. else
  1226. selected++;
  1227. if (selected > -1)
  1228. CloseMenu (true);
  1229. OpenMenu (selected);
  1230. SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current);
  1231. break;
  1232. case true:
  1233. if (UseKeysUpDownAsKeysLeftRight) {
  1234. CloseMenu (false, true);
  1235. NextMenu ();
  1236. } else {
  1237. var subMenu = openCurrentMenu.barItems.SubMenu (openCurrentMenu.barItems.Children [openCurrentMenu.current]);
  1238. if ((selectedSub == -1 || openSubMenu == null || openSubMenu?.Count == selectedSub) && subMenu == null) {
  1239. if (openSubMenu != null)
  1240. CloseMenu (false, true);
  1241. NextMenu ();
  1242. } else if (subMenu != null ||
  1243. !openCurrentMenu.barItems.Children [openCurrentMenu.current].IsFromSubMenu)
  1244. selectedSub++;
  1245. else
  1246. return;
  1247. SetNeedsDisplay ();
  1248. openCurrentMenu.CheckSubMenu ();
  1249. }
  1250. break;
  1251. }
  1252. }
  1253. bool openedByHotKey;
  1254. internal bool FindAndOpenMenuByHotkey (KeyEvent kb)
  1255. {
  1256. //int pos = 0;
  1257. var c = ((uint)kb.Key & (uint)Key.CharMask);
  1258. for (int i = 0; i < Menus.Length; i++) {
  1259. // TODO: this code is duplicated, hotkey should be part of the MenuBarItem
  1260. var mi = Menus [i];
  1261. int p = mi.Title.IndexOf ('_');
  1262. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1263. if (Char.ToUpperInvariant ((char)mi.Title [p + 1]) == c) {
  1264. ProcessMenu (i, mi);
  1265. return true;
  1266. }
  1267. }
  1268. }
  1269. return false;
  1270. }
  1271. internal bool FindAndOpenMenuByShortcut (KeyEvent kb, MenuItem [] children = null)
  1272. {
  1273. if (children == null) {
  1274. children = Menus;
  1275. }
  1276. var key = kb.KeyValue;
  1277. var keys = ShortcutHelper.GetModifiersKey (kb);
  1278. key |= (int)keys;
  1279. for (int i = 0; i < children.Length; i++) {
  1280. var mi = children [i];
  1281. if (mi == null) {
  1282. continue;
  1283. }
  1284. if ((!(mi is MenuBarItem mbiTopLevel) || mbiTopLevel.IsTopLevel) && mi.Shortcut != Key.Null && mi.Shortcut == (Key)key) {
  1285. var action = mi.Action;
  1286. if (action != null) {
  1287. Application.MainLoop.AddIdle (() => {
  1288. action ();
  1289. return false;
  1290. });
  1291. }
  1292. return true;
  1293. }
  1294. if (mi is MenuBarItem menuBarItem && !menuBarItem.IsTopLevel && FindAndOpenMenuByShortcut (kb, menuBarItem.Children)) {
  1295. return true;
  1296. }
  1297. }
  1298. return false;
  1299. }
  1300. private void ProcessMenu (int i, MenuBarItem mi)
  1301. {
  1302. if (selected < 0) {
  1303. return;
  1304. }
  1305. if (mi.IsTopLevel) {
  1306. var menu = new Menu (this, i, 0, mi);
  1307. menu.Run (mi.Action);
  1308. menu.Dispose ();
  1309. } else {
  1310. openedByHotKey = true;
  1311. Application.GrabMouse (this);
  1312. selected = i;
  1313. OpenMenu (i);
  1314. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  1315. CloseMenu ();
  1316. }
  1317. openCurrentMenu.CheckSubMenu ();
  1318. }
  1319. SetNeedsDisplay ();
  1320. }
  1321. ///<inheritdoc/>
  1322. public override bool ProcessHotKey (KeyEvent kb)
  1323. {
  1324. if (kb.Key == Key.F9) {
  1325. if (!IsMenuOpen)
  1326. OpenMenu ();
  1327. else
  1328. CloseAllMenus ();
  1329. return true;
  1330. }
  1331. // To ncurses simulate a AltMask key pressing Alt+Space because
  1332. // it can�t detect an alone special key down was pressed.
  1333. if (kb.IsAlt && kb.Key == Key.AltMask && openMenu == null) {
  1334. OnKeyDown (kb);
  1335. OnKeyUp (kb);
  1336. return true;
  1337. } else if (kb.IsAlt && !kb.IsCtrl && !kb.IsShift) {
  1338. if (FindAndOpenMenuByHotkey (kb)) return true;
  1339. }
  1340. //var kc = kb.KeyValue;
  1341. return base.ProcessHotKey (kb);
  1342. }
  1343. ///<inheritdoc/>
  1344. public override bool ProcessKey (KeyEvent kb)
  1345. {
  1346. switch (kb.Key) {
  1347. case Key.CursorLeft:
  1348. MoveLeft ();
  1349. return true;
  1350. case Key.CursorRight:
  1351. MoveRight ();
  1352. return true;
  1353. case Key.Esc:
  1354. case Key.C | Key.CtrlMask:
  1355. CloseMenuBar ();
  1356. return true;
  1357. case Key.CursorDown:
  1358. case Key.Enter:
  1359. ProcessMenu (selected, Menus [selected]);
  1360. return true;
  1361. default:
  1362. var key = kb.KeyValue;
  1363. if ((key >= 'a' && key <= 'z') || (key >= 'A' && key <= 'Z') || (key >= '0' && key <= '9')) {
  1364. char c = Char.ToUpper ((char)key);
  1365. if (selected == -1 || Menus [selected].IsTopLevel)
  1366. return false;
  1367. foreach (var mi in Menus [selected].Children) {
  1368. if (mi == null)
  1369. continue;
  1370. int p = mi.Title.IndexOf ('_');
  1371. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1372. if (mi.Title [p + 1] == c) {
  1373. Selected (mi);
  1374. return true;
  1375. }
  1376. }
  1377. }
  1378. }
  1379. return false;
  1380. }
  1381. }
  1382. void CloseMenuBar ()
  1383. {
  1384. CloseMenu ();
  1385. if (openedByAltKey) {
  1386. openedByAltKey = false;
  1387. LastFocused?.SetFocus ();
  1388. }
  1389. SetNeedsDisplay ();
  1390. }
  1391. void MoveRight ()
  1392. {
  1393. selected = (selected + 1) % Menus.Length;
  1394. OpenMenu (selected);
  1395. SetNeedsDisplay ();
  1396. }
  1397. void MoveLeft ()
  1398. {
  1399. selected--;
  1400. if (selected < 0)
  1401. selected = Menus.Length - 1;
  1402. OpenMenu (selected);
  1403. SetNeedsDisplay ();
  1404. }
  1405. ///<inheritdoc/>
  1406. public override bool ProcessColdKey (KeyEvent kb)
  1407. {
  1408. return FindAndOpenMenuByShortcut (kb);
  1409. }
  1410. ///<inheritdoc/>
  1411. public override bool MouseEvent (MouseEvent me)
  1412. {
  1413. if (!handled && !HandleGrabView (me, this)) {
  1414. return false;
  1415. }
  1416. handled = false;
  1417. if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked || me.Flags == MouseFlags.Button1Clicked ||
  1418. (me.Flags == MouseFlags.ReportMousePosition && selected > -1) ||
  1419. (me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && selected > -1)) {
  1420. int pos = 1;
  1421. int cx = me.X;
  1422. for (int i = 0; i < Menus.Length; i++) {
  1423. if (cx >= pos && cx < pos + 1 + Menus [i].TitleLength + Menus [i].Help.RuneCount + 2) {
  1424. if (me.Flags == MouseFlags.Button1Clicked) {
  1425. if (Menus [i].IsTopLevel) {
  1426. var menu = new Menu (this, i, 0, Menus [i]);
  1427. menu.Run (Menus [i].Action);
  1428. menu.Dispose ();
  1429. }
  1430. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked) {
  1431. if (IsMenuOpen && !Menus [i].IsTopLevel) {
  1432. CloseAllMenus ();
  1433. } else if (!Menus [i].IsTopLevel) {
  1434. Activate (i);
  1435. }
  1436. } else if (selected != i && selected > -1 && (me.Flags == MouseFlags.ReportMousePosition ||
  1437. me.Flags == MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)) {
  1438. if (IsMenuOpen) {
  1439. CloseMenu (true, false);
  1440. Activate (i);
  1441. }
  1442. } else {
  1443. if (IsMenuOpen)
  1444. Activate (i);
  1445. }
  1446. return true;
  1447. }
  1448. pos += 1 + Menus [i].TitleLength + 2;
  1449. }
  1450. }
  1451. return false;
  1452. }
  1453. internal bool handled;
  1454. internal bool HandleGrabView (MouseEvent me, View current)
  1455. {
  1456. if (Application.mouseGrabView != null) {
  1457. if (me.View is MenuBar || me.View is Menu) {
  1458. if (me.View != current) {
  1459. Application.UngrabMouse ();
  1460. var v = me.View;
  1461. Application.GrabMouse (v);
  1462. MouseEvent nme;
  1463. if (me.Y > -1) {
  1464. var newxy = v.ScreenToView (me.X, me.Y);
  1465. nme = new MouseEvent () {
  1466. X = newxy.X,
  1467. Y = newxy.Y,
  1468. Flags = me.Flags,
  1469. OfX = me.X - newxy.X,
  1470. OfY = me.Y - newxy.Y,
  1471. View = v
  1472. };
  1473. } else {
  1474. nme = new MouseEvent () {
  1475. X = me.X + current.Frame.X,
  1476. Y = 0,
  1477. Flags = me.Flags,
  1478. View = v
  1479. };
  1480. }
  1481. v.MouseEvent (nme);
  1482. return false;
  1483. }
  1484. } else if (!(me.View is MenuBar || me.View is Menu) && (me.Flags.HasFlag (MouseFlags.Button1Clicked) ||
  1485. me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked)) {
  1486. Application.UngrabMouse ();
  1487. CloseAllMenus ();
  1488. handled = false;
  1489. return false;
  1490. } else {
  1491. handled = false;
  1492. return false;
  1493. }
  1494. } else if (!IsMenuOpen && (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked || me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))) {
  1495. Application.GrabMouse (current);
  1496. } else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu)) {
  1497. Application.GrabMouse (me.View);
  1498. } else {
  1499. handled = false;
  1500. return false;
  1501. }
  1502. //if (me.View != this && me.Flags != MouseFlags.Button1Pressed)
  1503. // return true;
  1504. //else if (me.View != this && me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1505. // Application.UngrabMouse ();
  1506. // host.CloseAllMenus ();
  1507. // return true;
  1508. //}
  1509. //if (!(me.View is MenuBar) && !(me.View is Menu) && me.Flags != MouseFlags.Button1Pressed))
  1510. // return false;
  1511. //if (Application.mouseGrabView != null) {
  1512. // if (me.View is MenuBar || me.View is Menu) {
  1513. // me.X -= me.OfX;
  1514. // me.Y -= me.OfY;
  1515. // me.View.MouseEvent (me);
  1516. // return true;
  1517. // } else if (!(me.View is MenuBar || me.View is Menu) && me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1518. // Application.UngrabMouse ();
  1519. // CloseAllMenus ();
  1520. // }
  1521. //} else if (!isMenuClosed && selected == -1 && me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1522. // Application.GrabMouse (this);
  1523. // return true;
  1524. //}
  1525. //if (Application.mouseGrabView != null) {
  1526. // if (Application.mouseGrabView == me.View && me.View == current) {
  1527. // me.X -= me.OfX;
  1528. // me.Y -= me.OfY;
  1529. // } else if (me.View != current && me.View is MenuBar && me.View is Menu) {
  1530. // Application.UngrabMouse ();
  1531. // Application.GrabMouse (me.View);
  1532. // } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1533. // Application.UngrabMouse ();
  1534. // CloseMenu ();
  1535. // }
  1536. //} else if ((!isMenuClosed && selected > -1)) {
  1537. // Application.GrabMouse (current);
  1538. //}
  1539. handled = true;
  1540. return true;
  1541. }
  1542. ///<inheritdoc/>
  1543. public override bool OnEnter (View view)
  1544. {
  1545. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  1546. return base.OnEnter (view);
  1547. }
  1548. }
  1549. /// <summary>
  1550. /// An <see cref="EventArgs"/> which allows passing a cancelable menu opening event or replacing with a new <see cref="MenuBarItem"/>.
  1551. /// </summary>
  1552. public class MenuOpeningEventArgs : EventArgs {
  1553. /// <summary>
  1554. /// The current <see cref="MenuBarItem"/> parent.
  1555. /// </summary>
  1556. public MenuBarItem CurrentMenu { get; }
  1557. /// <summary>
  1558. /// The new <see cref="MenuBarItem"/> to be replaced.
  1559. /// </summary>
  1560. public MenuBarItem NewMenuBarItem { get; set; }
  1561. /// <summary>
  1562. /// Flag that allows you to cancel the opening of the menu.
  1563. /// </summary>
  1564. public bool Cancel { get; set; }
  1565. /// <summary>
  1566. /// Initializes a new instance of <see cref="MenuOpeningEventArgs"/>
  1567. /// </summary>
  1568. /// <param name="currentMenu">The current <see cref="MenuBarItem"/> parent.</param>
  1569. public MenuOpeningEventArgs (MenuBarItem currentMenu)
  1570. {
  1571. CurrentMenu = currentMenu;
  1572. }
  1573. }
  1574. }