Menu.cs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679
  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 ColorScheme.Normal;
  379. }
  380. public override void Redraw (Rect bounds)
  381. {
  382. Driver.SetAttribute (ColorScheme.Normal);
  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 ? ColorScheme.Normal : i == current ? ColorScheme.Focus : ColorScheme.Normal);
  387. if (item == null) {
  388. Move (0, i + 1);
  389. Driver.AddRune (Driver.LeftTee);
  390. } else
  391. Move (1, i + 1);
  392. Driver.SetAttribute (DetermineColorSchemeFor (item, i));
  393. for (int p = 0; p < Frame.Width - 2; p++)
  394. if (item == null)
  395. Driver.AddRune (Driver.HLine);
  396. else if (p == Frame.Width - 3 && barItems.SubMenu (barItems.Children [i]) != null)
  397. Driver.AddRune (Driver.RightArrow);
  398. else
  399. Driver.AddRune (' ');
  400. if (item == null) {
  401. Move (Frame.Width - 1, i + 1);
  402. Driver.AddRune (Driver.RightTee);
  403. continue;
  404. }
  405. ustring textToDraw;
  406. var checkChar = Driver.Selected;
  407. var uncheckedChar = Driver.UnSelected;
  408. if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked)) {
  409. checkChar = Driver.Checked;
  410. uncheckedChar = Driver.UnChecked;
  411. }
  412. // Support Checked even though CheckType wasn't set
  413. if (item.Checked) {
  414. textToDraw = ustring.Make (new Rune [] { checkChar, ' ' }) + item.Title;
  415. } else if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked) || item.CheckType.HasFlag (MenuItemCheckStyle.Radio)) {
  416. textToDraw = ustring.Make (new Rune [] { uncheckedChar, ' ' }) + item.Title;
  417. } else {
  418. textToDraw = item.Title;
  419. }
  420. Move (2, i + 1);
  421. if (!item.IsEnabled ())
  422. DrawHotString (textToDraw, ColorScheme.Disabled, ColorScheme.Disabled);
  423. else
  424. DrawHotString (textToDraw,
  425. i == current ? ColorScheme.HotFocus : ColorScheme.HotNormal,
  426. i == current ? ColorScheme.Focus : ColorScheme.Normal);
  427. // The help string
  428. var l = item.ShortcutTag.RuneCount == 0 ? item.Help.RuneCount : item.Help.RuneCount + item.ShortcutTag.RuneCount + 2;
  429. Move (Frame.Width - l - 2, 1 + i);
  430. Driver.AddStr (item.Help);
  431. // The shortcut tag string
  432. if (!item.ShortcutTag.IsEmpty) {
  433. l = item.ShortcutTag.RuneCount;
  434. Move (Frame.Width - l - 2, 1 + i);
  435. Driver.AddStr (item.ShortcutTag);
  436. }
  437. }
  438. PositionCursor ();
  439. }
  440. public override void PositionCursor ()
  441. {
  442. if (host == null || host.IsMenuOpen)
  443. if (barItems.IsTopLevel) {
  444. host.PositionCursor ();
  445. } else
  446. Move (2, 1 + current);
  447. else
  448. host.PositionCursor ();
  449. }
  450. public void Run (Action action)
  451. {
  452. if (action == null)
  453. return;
  454. Application.UngrabMouse ();
  455. host.CloseAllMenus ();
  456. Application.Refresh ();
  457. Application.MainLoop.AddIdle (() => {
  458. action ();
  459. return false;
  460. });
  461. }
  462. public override bool OnLeave (View view)
  463. {
  464. return host.OnLeave (view);
  465. }
  466. public override bool OnKeyDown (KeyEvent keyEvent)
  467. {
  468. if (keyEvent.IsAlt) {
  469. host.CloseAllMenus ();
  470. return true;
  471. }
  472. return false;
  473. }
  474. public override bool ProcessHotKey (KeyEvent keyEvent)
  475. {
  476. // To ncurses simulate a AltMask key pressing Alt+Space because
  477. // it can�t detect an alone special key down was pressed.
  478. if (keyEvent.IsAlt && keyEvent.Key == Key.AltMask) {
  479. OnKeyDown (keyEvent);
  480. return true;
  481. }
  482. return false;
  483. }
  484. public override bool ProcessKey (KeyEvent kb)
  485. {
  486. switch (kb.Key) {
  487. case Key.Tab:
  488. host.CleanUp ();
  489. return true;
  490. case Key.CursorUp:
  491. return MoveUp ();
  492. case Key.CursorDown:
  493. return MoveDown ();
  494. case Key.CursorLeft:
  495. host.PreviousMenu (true);
  496. return true;
  497. case Key.CursorRight:
  498. host.NextMenu (barItems.IsTopLevel || (barItems.Children != null && current > -1 && current < barItems.Children.Length && barItems.Children [current].IsFromSubMenu) ? true : false);
  499. return true;
  500. case Key.Esc:
  501. Application.UngrabMouse ();
  502. host.CloseAllMenus ();
  503. return true;
  504. case Key.Enter:
  505. if (barItems.IsTopLevel) {
  506. Run (barItems.Action);
  507. } else if (current > -1) {
  508. Run (barItems.Children [current].Action);
  509. }
  510. return true;
  511. default:
  512. // TODO: rune-ify
  513. if (barItems.Children != null && Char.IsLetterOrDigit ((char)kb.KeyValue)) {
  514. var x = Char.ToUpper ((char)kb.KeyValue);
  515. foreach (var item in barItems.Children) {
  516. if (item == null) continue;
  517. if (item.IsEnabled () && item.HotKey == x) {
  518. host.CloseMenu ();
  519. Run (item.Action);
  520. return true;
  521. }
  522. }
  523. }
  524. break;
  525. }
  526. return false;
  527. }
  528. bool MoveDown ()
  529. {
  530. if (barItems.IsTopLevel) {
  531. return true;
  532. }
  533. bool disabled;
  534. do {
  535. current++;
  536. if (current >= barItems.Children.Length) {
  537. current = 0;
  538. }
  539. if (this != host.openCurrentMenu && barItems.Children [current].IsFromSubMenu && host.selectedSub > -1) {
  540. host.PreviousMenu (true);
  541. host.SelectEnabledItem (barItems.Children, current, out current);
  542. host.openCurrentMenu = this;
  543. }
  544. var item = barItems.Children [current];
  545. if (item?.IsEnabled () != true) {
  546. disabled = true;
  547. } else {
  548. disabled = false;
  549. }
  550. if (host.UseKeysUpDownAsKeysLeftRight && barItems.SubMenu (barItems.Children [current]) != null &&
  551. !disabled && host.IsMenuOpen) {
  552. CheckSubMenu ();
  553. break;
  554. }
  555. if (!host.IsMenuOpen) {
  556. host.OpenMenu (host.selected);
  557. }
  558. } while (barItems.Children [current] == null || disabled);
  559. SetNeedsDisplay ();
  560. return true;
  561. }
  562. bool MoveUp ()
  563. {
  564. if (barItems.IsTopLevel || current == -1) {
  565. return true;
  566. }
  567. bool disabled;
  568. do {
  569. current--;
  570. if (host.UseKeysUpDownAsKeysLeftRight) {
  571. if ((current == -1 || this != host.openCurrentMenu) && barItems.Children [current + 1].IsFromSubMenu && host.selectedSub > -1) {
  572. current++;
  573. host.PreviousMenu (true);
  574. if (current > 0) {
  575. current--;
  576. host.openCurrentMenu = this;
  577. }
  578. break;
  579. }
  580. }
  581. if (current < 0)
  582. current = barItems.Children.Length - 1;
  583. if (!host.SelectEnabledItem (barItems.Children, current, out current, false)) {
  584. current = 0;
  585. if (!host.SelectEnabledItem (barItems.Children, current, out current)) {
  586. host.CloseMenu ();
  587. }
  588. break;
  589. }
  590. var item = barItems.Children [current];
  591. if (item?.IsEnabled () != true) {
  592. disabled = true;
  593. } else {
  594. disabled = false;
  595. }
  596. if (host.UseKeysUpDownAsKeysLeftRight && barItems.SubMenu (barItems.Children [current]) != null &&
  597. !disabled && host.IsMenuOpen) {
  598. CheckSubMenu ();
  599. break;
  600. }
  601. } while (barItems.Children [current] == null || disabled);
  602. SetNeedsDisplay ();
  603. return true;
  604. }
  605. public override bool MouseEvent (MouseEvent me)
  606. {
  607. if (!host.handled && !host.HandleGrabView (me, this)) {
  608. return false;
  609. }
  610. host.handled = false;
  611. bool disabled;
  612. if (me.Flags == MouseFlags.Button1Clicked) {
  613. disabled = false;
  614. if (me.Y < 1)
  615. return true;
  616. var meY = me.Y - 1;
  617. if (meY >= barItems.Children.Length)
  618. return true;
  619. var item = barItems.Children [meY];
  620. if (item == null || !item.IsEnabled ()) disabled = true;
  621. if (item != null && !disabled)
  622. Run (barItems.Children [meY].Action);
  623. return true;
  624. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked ||
  625. me.Flags == MouseFlags.Button1TripleClicked || me.Flags == MouseFlags.ReportMousePosition ||
  626. me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  627. disabled = false;
  628. if (me.Y < 1 || me.Y - 1 >= barItems.Children.Length) {
  629. return true;
  630. }
  631. var item = barItems.Children [me.Y - 1];
  632. if (item == null || !item.IsEnabled ()) disabled = true;
  633. if (item != null && !disabled)
  634. current = me.Y - 1;
  635. CheckSubMenu ();
  636. return true;
  637. }
  638. return false;
  639. }
  640. internal void CheckSubMenu ()
  641. {
  642. if (current == -1 || barItems.Children [current] == null) {
  643. return;
  644. }
  645. var subMenu = barItems.SubMenu (barItems.Children [current]);
  646. if (subMenu != null) {
  647. int pos = -1;
  648. if (host.openSubMenu != null) {
  649. pos = host.openSubMenu.FindIndex (o => o?.barItems == subMenu);
  650. }
  651. if (pos == -1 && this != host.openCurrentMenu && subMenu.Children != host.openCurrentMenu.barItems.Children) {
  652. host.CloseMenu (false, true);
  653. }
  654. host.Activate (host.selected, pos, subMenu);
  655. } else if (host.openSubMenu?.Last ().barItems.IsSubMenuOf (barItems.Children [current]) == false) {
  656. host.CloseMenu (false, true);
  657. } else {
  658. SetNeedsDisplay ();
  659. }
  660. }
  661. int GetSubMenuIndex (MenuBarItem subMenu)
  662. {
  663. int pos = -1;
  664. if (this != null && Subviews.Count > 0) {
  665. Menu v = null;
  666. foreach (var menu in Subviews) {
  667. if (((Menu)menu).barItems == subMenu)
  668. v = (Menu)menu;
  669. }
  670. if (v != null)
  671. pos = Subviews.IndexOf (v);
  672. }
  673. return pos;
  674. }
  675. ///<inheritdoc/>
  676. public override bool OnEnter (View view)
  677. {
  678. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  679. return base.OnEnter (view);
  680. }
  681. }
  682. /// <summary>
  683. /// The MenuBar provides a menu for Terminal.Gui applications.
  684. /// </summary>
  685. /// <remarks>
  686. /// <para>
  687. /// The <see cref="MenuBar"/> appears on the first row of the terminal.
  688. /// </para>
  689. /// <para>
  690. /// The <see cref="MenuBar"/> provides global hotkeys for the application.
  691. /// </para>
  692. /// </remarks>
  693. public class MenuBar : View {
  694. /// <summary>
  695. /// Gets or sets the array of <see cref="MenuBarItem"/>s for the menu. Only set this when the <see cref="MenuBar"/> is vislble.
  696. /// </summary>
  697. /// <value>The menu array.</value>
  698. public MenuBarItem [] Menus { get; set; }
  699. internal int selected;
  700. internal int selectedSub;
  701. Action action;
  702. /// <summary>
  703. /// Used for change the navigation key style.
  704. /// </summary>
  705. public bool UseKeysUpDownAsKeysLeftRight { get; set; } = true;
  706. static ustring shortcutDelimiter = "+";
  707. /// <summary>
  708. /// Used for change the shortcut delimiter separator.
  709. /// </summary>
  710. public static ustring ShortcutDelimiter {
  711. get => shortcutDelimiter;
  712. set {
  713. if (shortcutDelimiter != value) {
  714. shortcutDelimiter = value == ustring.Empty ? " " : value;
  715. }
  716. }
  717. }
  718. /// <summary>
  719. /// Initializes a new instance of the <see cref="MenuBar"/>.
  720. /// </summary>
  721. public MenuBar () : this (new MenuBarItem [] { }) { }
  722. /// <summary>
  723. /// Initializes a new instance of the <see cref="MenuBar"/> class with the specified set of toplevel menu items.
  724. /// </summary>
  725. /// <param name="menus">Individual menu items; a null item will result in a separator being drawn.</param>
  726. public MenuBar (MenuBarItem [] menus) : base ()
  727. {
  728. X = 0;
  729. Y = 0;
  730. Width = Dim.Fill ();
  731. Height = 1;
  732. Menus = menus;
  733. //CanFocus = true;
  734. selected = -1;
  735. selectedSub = -1;
  736. ColorScheme = Colors.Menu;
  737. WantMousePositionReports = true;
  738. IsMenuOpen = false;
  739. }
  740. bool openedByAltKey;
  741. bool isCleaning;
  742. ///<inheritdoc/>
  743. public override bool OnLeave (View view)
  744. {
  745. if ((!(view is MenuBar) && !(view is Menu) || !(view is MenuBar) && !(view is Menu) && openMenu != null) && !isCleaning && !reopen) {
  746. CleanUp ();
  747. return true;
  748. }
  749. return false;
  750. }
  751. ///<inheritdoc/>
  752. public override bool OnKeyDown (KeyEvent keyEvent)
  753. {
  754. if (keyEvent.IsAlt || (keyEvent.IsCtrl && keyEvent.Key == (Key.CtrlMask | Key.Space))) {
  755. openedByAltKey = true;
  756. SetNeedsDisplay ();
  757. openedByHotKey = false;
  758. }
  759. return false;
  760. }
  761. ///<inheritdoc/>
  762. public override bool OnKeyUp (KeyEvent keyEvent)
  763. {
  764. if (keyEvent.IsAlt || (keyEvent.IsCtrl && keyEvent.Key == (Key.CtrlMask | Key.Space))) {
  765. // User pressed Alt - this may be a precursor to a menu accelerator (e.g. Alt-F)
  766. if (openedByAltKey && !IsMenuOpen && openMenu == null && (((uint)keyEvent.Key & (uint)Key.CharMask) == 0
  767. || ((uint)keyEvent.Key & (uint)Key.CharMask) == (uint)Key.Space)) {
  768. // There's no open menu, the first menu item should be highlight.
  769. // The right way to do this is to SetFocus(MenuBar), but for some reason
  770. // that faults.
  771. //Activate (0);
  772. //StartMenu ();
  773. IsMenuOpen = true;
  774. selected = 0;
  775. CanFocus = true;
  776. lastFocused = SuperView.MostFocused;
  777. SetFocus ();
  778. SetNeedsDisplay ();
  779. Application.GrabMouse (this);
  780. } else if (!openedByHotKey) {
  781. // There's an open menu. If this Alt key-up is a pre-cursor to an accelerator
  782. // we don't want to close the menu because it'll flash.
  783. // How to deal with that?
  784. CleanUp ();
  785. }
  786. return true;
  787. }
  788. return false;
  789. }
  790. internal void CleanUp ()
  791. {
  792. isCleaning = true;
  793. if (openMenu != null) {
  794. CloseAllMenus ();
  795. }
  796. openedByAltKey = false;
  797. IsMenuOpen = false;
  798. selected = -1;
  799. CanFocus = false;
  800. if (lastFocused != null) {
  801. lastFocused.SetFocus ();
  802. }
  803. SetNeedsDisplay ();
  804. Application.UngrabMouse ();
  805. isCleaning = false;
  806. }
  807. ///<inheritdoc/>
  808. public override void Redraw (Rect bounds)
  809. {
  810. Move (0, 0);
  811. Driver.SetAttribute (ColorScheme.Normal);
  812. for (int i = 0; i < Frame.Width; i++)
  813. Driver.AddRune (' ');
  814. Move (1, 0);
  815. int pos = 1;
  816. for (int i = 0; i < Menus.Length; i++) {
  817. var menu = Menus [i];
  818. Move (pos, 0);
  819. Attribute hotColor, normalColor;
  820. if (i == selected && IsMenuOpen) {
  821. hotColor = i == selected ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  822. normalColor = i == selected ? ColorScheme.Focus : ColorScheme.Normal;
  823. } else if (openedByAltKey) {
  824. hotColor = ColorScheme.HotNormal;
  825. normalColor = ColorScheme.Normal;
  826. } else {
  827. hotColor = ColorScheme.Normal;
  828. normalColor = ColorScheme.Normal;
  829. }
  830. DrawHotString (menu.Help.IsEmpty ? $" {menu.Title} " : $" {menu.Title} {menu.Help} ", hotColor, normalColor);
  831. pos += 1 + menu.TitleLength + (menu.Help.Length > 0 ? menu.Help.Length + 2 : 0) + 2;
  832. }
  833. PositionCursor ();
  834. }
  835. ///<inheritdoc/>
  836. public override void PositionCursor ()
  837. {
  838. if (selected == -1 && HasFocus && Menus.Length > 0) {
  839. selected = 0;
  840. }
  841. int pos = 0;
  842. for (int i = 0; i < Menus.Length; i++) {
  843. if (i == selected) {
  844. pos++;
  845. if (IsMenuOpen)
  846. Move (pos + 1, 0);
  847. else {
  848. Move (pos + 1, 0);
  849. }
  850. return;
  851. } else if (IsMenuOpen) {
  852. pos += 1 + Menus [i].TitleLength + (Menus [i].Help.Length > 0 ? Menus [i].Help.Length + 2 : 0) + 2;
  853. } else {
  854. pos += 2 + Menus [i].TitleLength + (Menus [i].Help.Length > 0 ? Menus [i].Help.Length + 2 : 0) + 1;
  855. }
  856. }
  857. //Move (0, 0);
  858. }
  859. void Selected (MenuItem item)
  860. {
  861. // TODO: Running = false;
  862. action = item.Action;
  863. }
  864. /// <summary>
  865. /// Raised as a menu is opening.
  866. /// </summary>
  867. public event Action<MenuOpeningEventArgs> MenuOpening;
  868. /// <summary>
  869. /// Raised when a menu is closing.
  870. /// </summary>
  871. public event Action MenuClosing;
  872. internal Menu openMenu;
  873. internal Menu openCurrentMenu;
  874. internal List<Menu> openSubMenu;
  875. View previousFocused;
  876. internal bool isMenuOpening;
  877. internal bool isMenuClosing;
  878. /// <summary>
  879. /// True if the menu is open; otherwise false.
  880. /// </summary>
  881. public bool IsMenuOpen { get; protected set; }
  882. /// <summary>
  883. /// Virtual method that will invoke the <see cref="MenuOpening"/> event if it's defined.
  884. /// </summary>
  885. /// <param name="currentMenu">The current menu to be replaced.</param>
  886. /// /// <returns>Returns the <see cref="MenuOpeningEventArgs"/></returns>
  887. public virtual MenuOpeningEventArgs OnMenuOpening (MenuBarItem currentMenu)
  888. {
  889. var ev = new MenuOpeningEventArgs (currentMenu);
  890. MenuOpening?.Invoke (ev);
  891. return ev;
  892. }
  893. /// <summary>
  894. /// Virtual method that will invoke the <see cref="MenuClosing"/>
  895. /// </summary>
  896. public virtual void OnMenuClosing ()
  897. {
  898. MenuClosing?.Invoke ();
  899. }
  900. View lastFocused;
  901. /// <summary>
  902. /// Get the lasted focused view before open the menu.
  903. /// </summary>
  904. public View LastFocused { get; private set; }
  905. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem subMenu = null)
  906. {
  907. isMenuOpening = true;
  908. var newMenu = OnMenuOpening (Menus [index]);
  909. if (newMenu.Cancel) {
  910. return;
  911. }
  912. if (newMenu.NewMenuBarItem != null && Menus [index].Title == newMenu.NewMenuBarItem.Title) {
  913. Menus [index] = newMenu.NewMenuBarItem;
  914. }
  915. int pos = 0;
  916. switch (subMenu) {
  917. case null:
  918. lastFocused = lastFocused ?? SuperView?.MostFocused;
  919. if (openSubMenu != null)
  920. CloseMenu (false, true);
  921. if (openMenu != null) {
  922. SuperView.Remove (openMenu);
  923. openMenu.Dispose ();
  924. }
  925. for (int i = 0; i < index; i++)
  926. pos += Menus [i].Title.RuneCount + (Menus [i].Help.RuneCount > 0 ? Menus [i].Help.RuneCount + 2 : 0) + 2;
  927. openMenu = new Menu (this, pos, 1, Menus [index]);
  928. openCurrentMenu = openMenu;
  929. openCurrentMenu.previousSubFocused = openMenu;
  930. SuperView.Add (openMenu);
  931. openMenu.SetFocus ();
  932. break;
  933. default:
  934. if (openSubMenu == null)
  935. openSubMenu = new List<Menu> ();
  936. if (sIndex > -1) {
  937. RemoveSubMenu (sIndex);
  938. } else {
  939. var last = openSubMenu.Count > 0 ? openSubMenu.Last () : openMenu;
  940. openCurrentMenu = new Menu (this, last.Frame.Left + last.Frame.Width, last.Frame.Top + 1 + last.current, subMenu);
  941. openCurrentMenu.previousSubFocused = last.previousSubFocused;
  942. openSubMenu.Add (openCurrentMenu);
  943. SuperView.Add (openCurrentMenu);
  944. }
  945. selectedSub = openSubMenu.Count - 1;
  946. if (selectedSub > -1 && SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  947. openCurrentMenu.SetFocus ();
  948. }
  949. break;
  950. }
  951. isMenuOpening = false;
  952. IsMenuOpen = true;
  953. }
  954. /// <summary>
  955. /// Opens the current Menu programatically.
  956. /// </summary>
  957. public void OpenMenu ()
  958. {
  959. if (openMenu != null)
  960. return;
  961. selected = 0;
  962. SetNeedsDisplay ();
  963. previousFocused = SuperView.Focused;
  964. OpenMenu (selected);
  965. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  966. CloseMenu ();
  967. }
  968. openCurrentMenu.CheckSubMenu ();
  969. Application.GrabMouse (this);
  970. }
  971. // Activates the menu, handles either first focus, or activating an entry when it was already active
  972. // For mouse events.
  973. internal void Activate (int idx, int sIdx = -1, MenuBarItem subMenu = null)
  974. {
  975. selected = idx;
  976. selectedSub = sIdx;
  977. if (openMenu == null)
  978. previousFocused = SuperView.Focused;
  979. OpenMenu (idx, sIdx, subMenu);
  980. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  981. if (subMenu == null) {
  982. CloseMenu ();
  983. }
  984. }
  985. SetNeedsDisplay ();
  986. }
  987. internal bool SelectEnabledItem (IEnumerable<MenuItem> chldren, int current, out int newCurrent, bool forward = true)
  988. {
  989. if (chldren == null) {
  990. newCurrent = -1;
  991. return true;
  992. }
  993. IEnumerable<MenuItem> childrens;
  994. if (forward) {
  995. childrens = chldren;
  996. } else {
  997. childrens = chldren.Reverse ();
  998. }
  999. int count;
  1000. if (forward) {
  1001. count = -1;
  1002. } else {
  1003. count = childrens.Count ();
  1004. }
  1005. foreach (var child in childrens) {
  1006. if (forward) {
  1007. if (++count < current) {
  1008. continue;
  1009. }
  1010. } else {
  1011. if (--count > current) {
  1012. continue;
  1013. }
  1014. }
  1015. if (child == null || !child.IsEnabled ()) {
  1016. if (forward) {
  1017. current++;
  1018. } else {
  1019. current--;
  1020. }
  1021. } else {
  1022. newCurrent = current;
  1023. return true;
  1024. }
  1025. }
  1026. newCurrent = -1;
  1027. return false;
  1028. }
  1029. /// <summary>
  1030. /// Closes the current Menu programatically, if open.
  1031. /// </summary>
  1032. public void CloseMenu ()
  1033. {
  1034. CloseMenu (false, false);
  1035. }
  1036. bool reopen;
  1037. internal void CloseMenu (bool reopen = false, bool isSubMenu = false)
  1038. {
  1039. isMenuClosing = true;
  1040. this.reopen = reopen;
  1041. OnMenuClosing ();
  1042. switch (isSubMenu) {
  1043. case false:
  1044. if (openMenu != null) {
  1045. SuperView?.Remove (openMenu);
  1046. }
  1047. SetNeedsDisplay ();
  1048. if (previousFocused != null && previousFocused is Menu && openMenu != null && previousFocused.ToString () != openCurrentMenu.ToString ())
  1049. previousFocused.SetFocus ();
  1050. openMenu?.Dispose ();
  1051. openMenu = null;
  1052. if (lastFocused is Menu || lastFocused is MenuBar) {
  1053. lastFocused = null;
  1054. }
  1055. LastFocused = lastFocused;
  1056. lastFocused = null;
  1057. if (LastFocused != null) {
  1058. if (!reopen) {
  1059. selected = -1;
  1060. }
  1061. LastFocused.SetFocus ();
  1062. } else {
  1063. SetFocus ();
  1064. PositionCursor ();
  1065. }
  1066. IsMenuOpen = false;
  1067. break;
  1068. case true:
  1069. selectedSub = -1;
  1070. SetNeedsDisplay ();
  1071. RemoveAllOpensSubMenus ();
  1072. openCurrentMenu.previousSubFocused.SetFocus ();
  1073. openSubMenu = null;
  1074. IsMenuOpen = true;
  1075. break;
  1076. }
  1077. this.reopen = false;
  1078. isMenuClosing = false;
  1079. }
  1080. void RemoveSubMenu (int index)
  1081. {
  1082. if (openSubMenu == null)
  1083. return;
  1084. for (int i = openSubMenu.Count - 1; i > index; i--) {
  1085. isMenuClosing = true;
  1086. if (openSubMenu.Count - 1 > 0)
  1087. openSubMenu [i - 1].SetFocus ();
  1088. else
  1089. openMenu.SetFocus ();
  1090. if (openSubMenu != null) {
  1091. var menu = openSubMenu [i];
  1092. SuperView.Remove (menu);
  1093. openSubMenu.Remove (menu);
  1094. menu.Dispose ();
  1095. }
  1096. RemoveSubMenu (i);
  1097. }
  1098. if (openSubMenu.Count > 0)
  1099. openCurrentMenu = openSubMenu.Last ();
  1100. //if (openMenu.Subviews.Count == 0)
  1101. // return;
  1102. //if (index == 0) {
  1103. // //SuperView.SetFocus (previousSubFocused);
  1104. // FocusPrev ();
  1105. // return;
  1106. //}
  1107. //for (int i = openMenu.Subviews.Count - 1; i > index; i--) {
  1108. // isMenuClosing = true;
  1109. // if (openMenu.Subviews.Count - 1 > 0)
  1110. // SuperView.SetFocus (openMenu.Subviews [i - 1]);
  1111. // else
  1112. // SuperView.SetFocus (openMenu);
  1113. // if (openMenu != null) {
  1114. // Remove (openMenu.Subviews [i]);
  1115. // openMenu.Remove (openMenu.Subviews [i]);
  1116. // }
  1117. // RemoveSubMenu (i);
  1118. //}
  1119. isMenuClosing = false;
  1120. }
  1121. internal void RemoveAllOpensSubMenus ()
  1122. {
  1123. if (openSubMenu != null) {
  1124. foreach (var item in openSubMenu) {
  1125. SuperView.Remove (item);
  1126. item.Dispose ();
  1127. }
  1128. }
  1129. }
  1130. internal void CloseAllMenus ()
  1131. {
  1132. if (!isMenuOpening && !isMenuClosing) {
  1133. if (openSubMenu != null)
  1134. CloseMenu (false, true);
  1135. CloseMenu ();
  1136. if (LastFocused != null && LastFocused != this)
  1137. selected = -1;
  1138. }
  1139. IsMenuOpen = false;
  1140. openedByHotKey = false;
  1141. openedByAltKey = false;
  1142. }
  1143. View FindDeepestMenu (View view, ref int count)
  1144. {
  1145. count = count > 0 ? count : 0;
  1146. foreach (var menu in view.Subviews) {
  1147. if (menu is Menu) {
  1148. count++;
  1149. return FindDeepestMenu ((Menu)menu, ref count);
  1150. }
  1151. }
  1152. return view;
  1153. }
  1154. internal void PreviousMenu (bool isSubMenu = false)
  1155. {
  1156. switch (isSubMenu) {
  1157. case false:
  1158. if (selected <= 0)
  1159. selected = Menus.Length - 1;
  1160. else
  1161. selected--;
  1162. if (selected > -1)
  1163. CloseMenu (true, false);
  1164. OpenMenu (selected);
  1165. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current, false)) {
  1166. openCurrentMenu.current = 0;
  1167. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  1168. CloseMenu ();
  1169. }
  1170. break;
  1171. }
  1172. break;
  1173. case true:
  1174. if (selectedSub > -1) {
  1175. selectedSub--;
  1176. RemoveSubMenu (selectedSub);
  1177. SetNeedsDisplay ();
  1178. } else
  1179. PreviousMenu ();
  1180. break;
  1181. }
  1182. }
  1183. internal void NextMenu (bool isSubMenu = false)
  1184. {
  1185. switch (isSubMenu) {
  1186. case false:
  1187. if (selected == -1)
  1188. selected = 0;
  1189. else if (selected + 1 == Menus.Length)
  1190. selected = 0;
  1191. else
  1192. selected++;
  1193. if (selected > -1)
  1194. CloseMenu (true);
  1195. OpenMenu (selected);
  1196. SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current);
  1197. break;
  1198. case true:
  1199. if (UseKeysUpDownAsKeysLeftRight) {
  1200. CloseMenu (false, true);
  1201. NextMenu ();
  1202. } else {
  1203. var subMenu = openCurrentMenu.barItems.SubMenu (openCurrentMenu.barItems.Children [openCurrentMenu.current]);
  1204. if ((selectedSub == -1 || openSubMenu == null || openSubMenu?.Count == selectedSub) && subMenu == null) {
  1205. if (openSubMenu != null)
  1206. CloseMenu (false, true);
  1207. NextMenu ();
  1208. } else if (subMenu != null ||
  1209. !openCurrentMenu.barItems.Children [openCurrentMenu.current].IsFromSubMenu)
  1210. selectedSub++;
  1211. else
  1212. return;
  1213. SetNeedsDisplay ();
  1214. openCurrentMenu.CheckSubMenu ();
  1215. }
  1216. break;
  1217. }
  1218. }
  1219. bool openedByHotKey;
  1220. internal bool FindAndOpenMenuByHotkey (KeyEvent kb)
  1221. {
  1222. //int pos = 0;
  1223. var c = ((uint)kb.Key & (uint)Key.CharMask);
  1224. for (int i = 0; i < Menus.Length; i++) {
  1225. // TODO: this code is duplicated, hotkey should be part of the MenuBarItem
  1226. var mi = Menus [i];
  1227. int p = mi.Title.IndexOf ('_');
  1228. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1229. if (Char.ToUpperInvariant ((char)mi.Title [p + 1]) == c) {
  1230. ProcessMenu (i, mi);
  1231. return true;
  1232. }
  1233. }
  1234. }
  1235. return false;
  1236. }
  1237. internal bool FindAndOpenMenuByShortcut (KeyEvent kb, MenuItem [] children = null)
  1238. {
  1239. if (children == null) {
  1240. children = Menus;
  1241. }
  1242. var key = kb.KeyValue;
  1243. var keys = ShortcutHelper.GetModifiersKey (kb);
  1244. key |= (int)keys;
  1245. for (int i = 0; i < children.Length; i++) {
  1246. var mi = children [i];
  1247. if (mi == null) {
  1248. continue;
  1249. }
  1250. if ((!(mi is MenuBarItem mbiTopLevel) || mbiTopLevel.IsTopLevel) && mi.Shortcut != Key.Null && mi.Shortcut == (Key)key) {
  1251. var action = mi.Action;
  1252. if (action != null) {
  1253. Application.MainLoop.AddIdle (() => {
  1254. action ();
  1255. return false;
  1256. });
  1257. }
  1258. return true;
  1259. }
  1260. if (mi is MenuBarItem menuBarItem && !menuBarItem.IsTopLevel && FindAndOpenMenuByShortcut (kb, menuBarItem.Children)) {
  1261. return true;
  1262. }
  1263. }
  1264. return false;
  1265. }
  1266. private void ProcessMenu (int i, MenuBarItem mi)
  1267. {
  1268. if (mi.IsTopLevel) {
  1269. var menu = new Menu (this, i, 0, mi);
  1270. menu.Run (mi.Action);
  1271. menu.Dispose ();
  1272. } else {
  1273. openedByHotKey = true;
  1274. Application.GrabMouse (this);
  1275. selected = i;
  1276. OpenMenu (i);
  1277. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  1278. CloseMenu ();
  1279. }
  1280. openCurrentMenu.CheckSubMenu ();
  1281. }
  1282. }
  1283. ///<inheritdoc/>
  1284. public override bool ProcessHotKey (KeyEvent kb)
  1285. {
  1286. if (kb.Key == Key.F9) {
  1287. if (!IsMenuOpen)
  1288. OpenMenu ();
  1289. else
  1290. CloseAllMenus ();
  1291. return true;
  1292. }
  1293. // To ncurses simulate a AltMask key pressing Alt+Space because
  1294. // it can�t detect an alone special key down was pressed.
  1295. if (kb.IsAlt && kb.Key == Key.AltMask && openMenu == null) {
  1296. OnKeyDown (kb);
  1297. OnKeyUp (kb);
  1298. return true;
  1299. } else if (kb.IsAlt && !kb.IsCtrl && !kb.IsShift) {
  1300. if (FindAndOpenMenuByHotkey (kb)) return true;
  1301. }
  1302. //var kc = kb.KeyValue;
  1303. return base.ProcessHotKey (kb);
  1304. }
  1305. ///<inheritdoc/>
  1306. public override bool ProcessKey (KeyEvent kb)
  1307. {
  1308. switch (kb.Key) {
  1309. case Key.CursorLeft:
  1310. selected--;
  1311. if (selected < 0)
  1312. selected = Menus.Length - 1;
  1313. break;
  1314. case Key.CursorRight:
  1315. selected = (selected + 1) % Menus.Length;
  1316. break;
  1317. case Key.Esc:
  1318. case Key.C | Key.CtrlMask:
  1319. //TODO: Running = false;
  1320. CloseMenu ();
  1321. if (openedByAltKey) {
  1322. openedByAltKey = false;
  1323. LastFocused?.SetFocus ();
  1324. }
  1325. break;
  1326. case Key.CursorDown:
  1327. case Key.Enter:
  1328. if (selected > -1) {
  1329. ProcessMenu (selected, Menus [selected]);
  1330. }
  1331. break;
  1332. default:
  1333. var key = kb.KeyValue;
  1334. if ((key >= 'a' && key <= 'z') || (key >= 'A' && key <= 'Z') || (key >= '0' && key <= '9')) {
  1335. char c = Char.ToUpper ((char)key);
  1336. if (selected == -1 || Menus [selected].IsTopLevel)
  1337. return false;
  1338. foreach (var mi in Menus [selected].Children) {
  1339. if (mi == null)
  1340. continue;
  1341. int p = mi.Title.IndexOf ('_');
  1342. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1343. if (mi.Title [p + 1] == c) {
  1344. Selected (mi);
  1345. return true;
  1346. }
  1347. }
  1348. }
  1349. }
  1350. return false;
  1351. }
  1352. SetNeedsDisplay ();
  1353. return true;
  1354. }
  1355. ///<inheritdoc/>
  1356. public override bool ProcessColdKey (KeyEvent kb)
  1357. {
  1358. return FindAndOpenMenuByShortcut (kb);
  1359. }
  1360. ///<inheritdoc/>
  1361. public override bool MouseEvent (MouseEvent me)
  1362. {
  1363. if (!handled && !HandleGrabView (me, this)) {
  1364. return false;
  1365. }
  1366. handled = false;
  1367. if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked || me.Flags == MouseFlags.Button1Clicked ||
  1368. (me.Flags == MouseFlags.ReportMousePosition && selected > -1) ||
  1369. (me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && selected > -1)) {
  1370. int pos = 1;
  1371. int cx = me.X;
  1372. for (int i = 0; i < Menus.Length; i++) {
  1373. if (cx >= pos && cx < pos + 1 + Menus [i].TitleLength + Menus [i].Help.RuneCount + 2) {
  1374. if (me.Flags == MouseFlags.Button1Clicked) {
  1375. if (Menus [i].IsTopLevel) {
  1376. var menu = new Menu (this, i, 0, Menus [i]);
  1377. menu.Run (Menus [i].Action);
  1378. menu.Dispose ();
  1379. }
  1380. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked) {
  1381. if (IsMenuOpen && !Menus [i].IsTopLevel) {
  1382. CloseAllMenus ();
  1383. } else if (!Menus [i].IsTopLevel) {
  1384. Activate (i);
  1385. }
  1386. } else if (selected != i && selected > -1 && (me.Flags == MouseFlags.ReportMousePosition ||
  1387. me.Flags == MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)) {
  1388. if (IsMenuOpen) {
  1389. CloseMenu (true, false);
  1390. Activate (i);
  1391. }
  1392. } else {
  1393. if (IsMenuOpen)
  1394. Activate (i);
  1395. }
  1396. return true;
  1397. }
  1398. pos += 1 + Menus [i].TitleLength + 2;
  1399. }
  1400. }
  1401. return false;
  1402. }
  1403. internal bool handled;
  1404. internal bool HandleGrabView (MouseEvent me, View current)
  1405. {
  1406. if (Application.mouseGrabView != null) {
  1407. if (me.View is MenuBar || me.View is Menu) {
  1408. if (me.View != current) {
  1409. Application.UngrabMouse ();
  1410. var v = me.View;
  1411. Application.GrabMouse (v);
  1412. var newxy = v.ScreenToView (me.X, me.Y);
  1413. var nme = new MouseEvent () {
  1414. X = newxy.X,
  1415. Y = newxy.Y,
  1416. Flags = me.Flags,
  1417. OfX = me.X - newxy.X,
  1418. OfY = me.Y - newxy.Y,
  1419. View = v
  1420. };
  1421. v.MouseEvent (nme);
  1422. return false;
  1423. }
  1424. } else if (!(me.View is MenuBar || me.View is Menu) && (me.Flags.HasFlag (MouseFlags.Button1Clicked) ||
  1425. me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked)) {
  1426. Application.UngrabMouse ();
  1427. CloseAllMenus ();
  1428. handled = false;
  1429. return false;
  1430. } else {
  1431. handled = false;
  1432. return false;
  1433. }
  1434. } else if (!IsMenuOpen && (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked || me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))) {
  1435. Application.GrabMouse (current);
  1436. } else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu)) {
  1437. Application.GrabMouse (me.View);
  1438. } else {
  1439. handled = false;
  1440. return false;
  1441. }
  1442. //if (me.View != this && me.Flags != MouseFlags.Button1Pressed)
  1443. // return true;
  1444. //else if (me.View != this && me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1445. // Application.UngrabMouse ();
  1446. // host.CloseAllMenus ();
  1447. // return true;
  1448. //}
  1449. //if (!(me.View is MenuBar) && !(me.View is Menu) && me.Flags != MouseFlags.Button1Pressed))
  1450. // return false;
  1451. //if (Application.mouseGrabView != null) {
  1452. // if (me.View is MenuBar || me.View is Menu) {
  1453. // me.X -= me.OfX;
  1454. // me.Y -= me.OfY;
  1455. // me.View.MouseEvent (me);
  1456. // return true;
  1457. // } else if (!(me.View is MenuBar || me.View is Menu) && me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1458. // Application.UngrabMouse ();
  1459. // CloseAllMenus ();
  1460. // }
  1461. //} else if (!isMenuClosed && selected == -1 && me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1462. // Application.GrabMouse (this);
  1463. // return true;
  1464. //}
  1465. //if (Application.mouseGrabView != null) {
  1466. // if (Application.mouseGrabView == me.View && me.View == current) {
  1467. // me.X -= me.OfX;
  1468. // me.Y -= me.OfY;
  1469. // } else if (me.View != current && me.View is MenuBar && me.View is Menu) {
  1470. // Application.UngrabMouse ();
  1471. // Application.GrabMouse (me.View);
  1472. // } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1473. // Application.UngrabMouse ();
  1474. // CloseMenu ();
  1475. // }
  1476. //} else if ((!isMenuClosed && selected > -1)) {
  1477. // Application.GrabMouse (current);
  1478. //}
  1479. handled = true;
  1480. return true;
  1481. }
  1482. ///<inheritdoc/>
  1483. public override bool OnEnter (View view)
  1484. {
  1485. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  1486. return base.OnEnter (view);
  1487. }
  1488. }
  1489. /// <summary>
  1490. /// An <see cref="EventArgs"/> which allows passing a cancelable menu opening event or replacing with a new <see cref="MenuBarItem"/>.
  1491. /// </summary>
  1492. public class MenuOpeningEventArgs : EventArgs {
  1493. /// <summary>
  1494. /// The current <see cref="MenuBarItem"/> parent.
  1495. /// </summary>
  1496. public MenuBarItem CurrentMenu { get; }
  1497. /// <summary>
  1498. /// The new <see cref="MenuBarItem"/> to be replaced.
  1499. /// </summary>
  1500. public MenuBarItem NewMenuBarItem { get; set; }
  1501. /// <summary>
  1502. /// Flag that allows you to cancel the opening of the menu.
  1503. /// </summary>
  1504. public bool Cancel { get; set; }
  1505. /// <summary>
  1506. /// Initializes a new instance of <see cref="MenuOpeningEventArgs"/>
  1507. /// </summary>
  1508. /// <param name="currentMenu">The current <see cref="MenuBarItem"/> parent.</param>
  1509. public MenuOpeningEventArgs (MenuBarItem currentMenu)
  1510. {
  1511. CurrentMenu = currentMenu;
  1512. }
  1513. }
  1514. }