Menu.cs 46 KB

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