Menu.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622
  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 = Colors.Menu;
  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 = Colors.Menu;
  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.Right - 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. }
  676. /// <summary>
  677. /// The MenuBar provides a menu for Terminal.Gui applications.
  678. /// </summary>
  679. /// <remarks>
  680. /// <para>
  681. /// The <see cref="MenuBar"/> appears on the first row of the terminal.
  682. /// </para>
  683. /// <para>
  684. /// The <see cref="MenuBar"/> provides global hotkeys for the application.
  685. /// </para>
  686. /// </remarks>
  687. public class MenuBar : View {
  688. /// <summary>
  689. /// Gets or sets the array of <see cref="MenuBarItem"/>s for the menu. Only set this when the <see cref="MenuBar"/> is vislble.
  690. /// </summary>
  691. /// <value>The menu array.</value>
  692. public MenuBarItem [] Menus { get; set; }
  693. internal int selected;
  694. internal int selectedSub;
  695. Action action;
  696. /// <summary>
  697. /// Used for change the navigation key style.
  698. /// </summary>
  699. public bool UseKeysUpDownAsKeysLeftRight { get; set; } = true;
  700. static ustring shortcutDelimiter = "+";
  701. /// <summary>
  702. /// Used for change the shortcut delimiter separator.
  703. /// </summary>
  704. public static ustring ShortcutDelimiter {
  705. get => shortcutDelimiter;
  706. set {
  707. if (shortcutDelimiter != value) {
  708. shortcutDelimiter = value == ustring.Empty ? " " : value;
  709. }
  710. }
  711. }
  712. /// <summary>
  713. /// Initializes a new instance of the <see cref="MenuBar"/>.
  714. /// </summary>
  715. public MenuBar () : this (new MenuBarItem [] { }) { }
  716. /// <summary>
  717. /// Initializes a new instance of the <see cref="MenuBar"/> class with the specified set of toplevel menu items.
  718. /// </summary>
  719. /// <param name="menus">Individual menu items; a null item will result in a separator being drawn.</param>
  720. public MenuBar (MenuBarItem [] menus) : base ()
  721. {
  722. X = 0;
  723. Y = 0;
  724. Width = Dim.Fill ();
  725. Height = 1;
  726. Menus = menus;
  727. //CanFocus = true;
  728. selected = -1;
  729. selectedSub = -1;
  730. ColorScheme = Colors.Menu;
  731. WantMousePositionReports = true;
  732. IsMenuOpen = false;
  733. }
  734. bool openedByAltKey;
  735. bool isCleaning;
  736. ///<inheritdoc/>
  737. public override bool OnLeave (View view)
  738. {
  739. if ((!(view is MenuBar) && !(view is Menu) || !(view is MenuBar) && !(view is Menu) && openMenu != null) && !isCleaning && !reopen) {
  740. CleanUp ();
  741. return true;
  742. }
  743. return false;
  744. }
  745. ///<inheritdoc/>
  746. public override bool OnKeyDown (KeyEvent keyEvent)
  747. {
  748. if (keyEvent.IsAlt) {
  749. openedByAltKey = true;
  750. SetNeedsDisplay ();
  751. openedByHotKey = false;
  752. }
  753. return false;
  754. }
  755. ///<inheritdoc/>
  756. public override bool OnKeyUp (KeyEvent keyEvent)
  757. {
  758. if (keyEvent.IsAlt) {
  759. // User pressed Alt - this may be a precursor to a menu accelerator (e.g. Alt-F)
  760. if (!keyEvent.IsCtrl && openedByAltKey && !IsMenuOpen && openMenu == null && ((uint)keyEvent.Key & (uint)Key.CharMask) == 0) {
  761. // There's no open menu, the first menu item should be highlight.
  762. // The right way to do this is to SetFocus(MenuBar), but for some reason
  763. // that faults.
  764. //Activate (0);
  765. //StartMenu ();
  766. IsMenuOpen = true;
  767. selected = 0;
  768. CanFocus = true;
  769. lastFocused = SuperView.MostFocused;
  770. SetFocus ();
  771. SetNeedsDisplay ();
  772. Application.GrabMouse (this);
  773. } else if (!openedByHotKey) {
  774. // There's an open menu. If this Alt key-up is a pre-cursor to an accelerator
  775. // we don't want to close the menu because it'll flash.
  776. // How to deal with that?
  777. CleanUp ();
  778. }
  779. return true;
  780. }
  781. return false;
  782. }
  783. internal void CleanUp ()
  784. {
  785. isCleaning = true;
  786. if (openMenu != null) {
  787. CloseAllMenus ();
  788. }
  789. openedByAltKey = false;
  790. IsMenuOpen = false;
  791. selected = -1;
  792. CanFocus = false;
  793. if (lastFocused != null) {
  794. lastFocused.SetFocus ();
  795. }
  796. SetNeedsDisplay ();
  797. Application.UngrabMouse ();
  798. isCleaning = false;
  799. }
  800. ///<inheritdoc/>
  801. public override void Redraw (Rect bounds)
  802. {
  803. Move (0, 0);
  804. Driver.SetAttribute (Colors.Menu.Normal);
  805. for (int i = 0; i < Frame.Width; i++)
  806. Driver.AddRune (' ');
  807. Move (1, 0);
  808. int pos = 1;
  809. for (int i = 0; i < Menus.Length; i++) {
  810. var menu = Menus [i];
  811. Move (pos, 0);
  812. Attribute hotColor, normalColor;
  813. if (i == selected) {
  814. hotColor = i == selected ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  815. normalColor = i == selected ? ColorScheme.Focus : ColorScheme.Normal;
  816. } else if (openedByAltKey) {
  817. hotColor = ColorScheme.HotNormal;
  818. normalColor = ColorScheme.Normal;
  819. } else {
  820. hotColor = ColorScheme.Normal;
  821. normalColor = ColorScheme.Normal;
  822. }
  823. DrawHotString (menu.Help.IsEmpty ? $" {menu.Title} " : $" {menu.Title} {menu.Help} ", hotColor, normalColor);
  824. pos += 1 + menu.TitleLength + (menu.Help.Length > 0 ? menu.Help.Length + 2 : 0) + 2;
  825. }
  826. PositionCursor ();
  827. }
  828. ///<inheritdoc/>
  829. public override void PositionCursor ()
  830. {
  831. int pos = 0;
  832. for (int i = 0; i < Menus.Length; i++) {
  833. if (i == selected) {
  834. pos++;
  835. if (IsMenuOpen)
  836. Move (pos + 1, 0);
  837. else {
  838. Move (pos + 1, 0);
  839. }
  840. return;
  841. } else if (IsMenuOpen) {
  842. pos += 1 + Menus [i].TitleLength + (Menus [i].Help.Length > 0 ? Menus [i].Help.Length + 2 : 0) + 2;
  843. } else {
  844. pos += 2 + Menus [i].TitleLength + (Menus [i].Help.Length > 0 ? Menus [i].Help.Length + 2 : 0) + 1;
  845. }
  846. }
  847. //Move (0, 0);
  848. }
  849. void Selected (MenuItem item)
  850. {
  851. // TODO: Running = false;
  852. action = item.Action;
  853. }
  854. /// <summary>
  855. /// Raised as a menu is opening.
  856. /// </summary>
  857. public event Action MenuOpening;
  858. /// <summary>
  859. /// Raised when a menu is closing.
  860. /// </summary>
  861. public event Action MenuClosing;
  862. internal Menu openMenu;
  863. internal Menu openCurrentMenu;
  864. internal List<Menu> openSubMenu;
  865. View previousFocused;
  866. internal bool isMenuOpening;
  867. internal bool isMenuClosing;
  868. /// <summary>
  869. /// True if the menu is open; otherwise false.
  870. /// </summary>
  871. public bool IsMenuOpen { get; protected set; }
  872. /// <summary>
  873. /// Virtual method that will invoke the <see cref="MenuOpening"/>
  874. /// </summary>
  875. public virtual void OnMenuOpening ()
  876. {
  877. MenuOpening?.Invoke ();
  878. }
  879. /// <summary>
  880. /// Virtual method that will invoke the <see cref="MenuClosing"/>
  881. /// </summary>
  882. public virtual void OnMenuClosing ()
  883. {
  884. MenuClosing?.Invoke ();
  885. }
  886. View lastFocused;
  887. /// <summary>
  888. /// Get the lasted focused view before open the menu.
  889. /// </summary>
  890. public View LastFocused { get; private set; }
  891. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem subMenu = null)
  892. {
  893. isMenuOpening = true;
  894. OnMenuOpening ();
  895. int pos = 0;
  896. switch (subMenu) {
  897. case null:
  898. lastFocused = lastFocused ?? SuperView.MostFocused;
  899. if (openSubMenu != null)
  900. CloseMenu (false, true);
  901. if (openMenu != null) {
  902. SuperView.Remove (openMenu);
  903. openMenu.Dispose ();
  904. }
  905. for (int i = 0; i < index; i++)
  906. pos += Menus [i].Title.RuneCount + (Menus [i].Help.RuneCount > 0 ? Menus [i].Help.RuneCount + 2 : 0) + 2;
  907. openMenu = new Menu (this, pos, 1, Menus [index]);
  908. openCurrentMenu = openMenu;
  909. openCurrentMenu.previousSubFocused = openMenu;
  910. SuperView.Add (openMenu);
  911. openMenu.SetFocus ();
  912. break;
  913. default:
  914. if (openSubMenu == null)
  915. openSubMenu = new List<Menu> ();
  916. if (sIndex > -1) {
  917. RemoveSubMenu (sIndex);
  918. } else {
  919. var last = openSubMenu.Count > 0 ? openSubMenu.Last () : openMenu;
  920. openCurrentMenu = new Menu (this, last.Frame.Left + last.Frame.Width, last.Frame.Top + 1 + last.current, subMenu);
  921. openCurrentMenu.previousSubFocused = last.previousSubFocused;
  922. openSubMenu.Add (openCurrentMenu);
  923. SuperView.Add (openCurrentMenu);
  924. }
  925. selectedSub = openSubMenu.Count - 1;
  926. if (selectedSub > -1 && SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  927. openCurrentMenu.SetFocus ();
  928. }
  929. break;
  930. }
  931. isMenuOpening = false;
  932. IsMenuOpen = true;
  933. }
  934. /// <summary>
  935. /// Opens the current Menu programatically.
  936. /// </summary>
  937. public void OpenMenu ()
  938. {
  939. if (openMenu != null)
  940. return;
  941. selected = 0;
  942. SetNeedsDisplay ();
  943. previousFocused = SuperView.Focused;
  944. OpenMenu (selected);
  945. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  946. CloseMenu ();
  947. }
  948. openCurrentMenu.CheckSubMenu ();
  949. Application.GrabMouse (this);
  950. }
  951. // Activates the menu, handles either first focus, or activating an entry when it was already active
  952. // For mouse events.
  953. internal void Activate (int idx, int sIdx = -1, MenuBarItem subMenu = null)
  954. {
  955. selected = idx;
  956. selectedSub = sIdx;
  957. if (openMenu == null)
  958. previousFocused = SuperView.Focused;
  959. OpenMenu (idx, sIdx, subMenu);
  960. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  961. if (subMenu == null) {
  962. CloseMenu ();
  963. }
  964. }
  965. SetNeedsDisplay ();
  966. }
  967. internal bool SelectEnabledItem (IEnumerable<MenuItem> chldren, int current, out int newCurrent, bool forward = true)
  968. {
  969. if (chldren == null) {
  970. newCurrent = -1;
  971. return true;
  972. }
  973. IEnumerable<MenuItem> childrens;
  974. if (forward) {
  975. childrens = chldren;
  976. } else {
  977. childrens = chldren.Reverse ();
  978. }
  979. int count;
  980. if (forward) {
  981. count = -1;
  982. } else {
  983. count = childrens.Count ();
  984. }
  985. foreach (var child in childrens) {
  986. if (forward) {
  987. if (++count < current) {
  988. continue;
  989. }
  990. } else {
  991. if (--count > current) {
  992. continue;
  993. }
  994. }
  995. if (child == null || !child.IsEnabled ()) {
  996. if (forward) {
  997. current++;
  998. } else {
  999. current--;
  1000. }
  1001. } else {
  1002. newCurrent = current;
  1003. return true;
  1004. }
  1005. }
  1006. newCurrent = -1;
  1007. return false;
  1008. }
  1009. /// <summary>
  1010. /// Closes the current Menu programatically, if open.
  1011. /// </summary>
  1012. public void CloseMenu ()
  1013. {
  1014. CloseMenu (false, false);
  1015. }
  1016. bool reopen;
  1017. internal void CloseMenu (bool reopen = false, bool isSubMenu = false)
  1018. {
  1019. isMenuClosing = true;
  1020. this.reopen = reopen;
  1021. OnMenuClosing ();
  1022. switch (isSubMenu) {
  1023. case false:
  1024. if (openMenu != null) {
  1025. SuperView?.Remove (openMenu);
  1026. }
  1027. SetNeedsDisplay ();
  1028. if (previousFocused != null && previousFocused is Menu && openMenu != null && previousFocused.ToString () != openCurrentMenu.ToString ())
  1029. previousFocused.SetFocus ();
  1030. openMenu?.Dispose ();
  1031. openMenu = null;
  1032. if (lastFocused is Menu || lastFocused is MenuBar) {
  1033. lastFocused = null;
  1034. }
  1035. LastFocused = lastFocused;
  1036. lastFocused = null;
  1037. if (LastFocused != null) {
  1038. if (!reopen) {
  1039. selected = -1;
  1040. }
  1041. LastFocused.SetFocus ();
  1042. } else {
  1043. SetFocus ();
  1044. PositionCursor ();
  1045. }
  1046. IsMenuOpen = false;
  1047. break;
  1048. case true:
  1049. selectedSub = -1;
  1050. SetNeedsDisplay ();
  1051. RemoveAllOpensSubMenus ();
  1052. openCurrentMenu.previousSubFocused.SetFocus ();
  1053. openSubMenu = null;
  1054. IsMenuOpen = true;
  1055. break;
  1056. }
  1057. this.reopen = false;
  1058. isMenuClosing = false;
  1059. }
  1060. void RemoveSubMenu (int index)
  1061. {
  1062. if (openSubMenu == null)
  1063. return;
  1064. for (int i = openSubMenu.Count - 1; i > index; i--) {
  1065. isMenuClosing = true;
  1066. if (openSubMenu.Count - 1 > 0)
  1067. openSubMenu [i - 1].SetFocus ();
  1068. else
  1069. openMenu.SetFocus ();
  1070. if (openSubMenu != null) {
  1071. var menu = openSubMenu [i];
  1072. SuperView.Remove (menu);
  1073. openSubMenu.Remove (menu);
  1074. menu.Dispose ();
  1075. }
  1076. RemoveSubMenu (i);
  1077. }
  1078. if (openSubMenu.Count > 0)
  1079. openCurrentMenu = openSubMenu.Last ();
  1080. //if (openMenu.Subviews.Count == 0)
  1081. // return;
  1082. //if (index == 0) {
  1083. // //SuperView.SetFocus (previousSubFocused);
  1084. // FocusPrev ();
  1085. // return;
  1086. //}
  1087. //for (int i = openMenu.Subviews.Count - 1; i > index; i--) {
  1088. // isMenuClosing = true;
  1089. // if (openMenu.Subviews.Count - 1 > 0)
  1090. // SuperView.SetFocus (openMenu.Subviews [i - 1]);
  1091. // else
  1092. // SuperView.SetFocus (openMenu);
  1093. // if (openMenu != null) {
  1094. // Remove (openMenu.Subviews [i]);
  1095. // openMenu.Remove (openMenu.Subviews [i]);
  1096. // }
  1097. // RemoveSubMenu (i);
  1098. //}
  1099. isMenuClosing = false;
  1100. }
  1101. internal void RemoveAllOpensSubMenus ()
  1102. {
  1103. if (openSubMenu != null) {
  1104. foreach (var item in openSubMenu) {
  1105. SuperView.Remove (item);
  1106. item.Dispose ();
  1107. }
  1108. }
  1109. }
  1110. internal void CloseAllMenus ()
  1111. {
  1112. if (!isMenuOpening && !isMenuClosing) {
  1113. if (openSubMenu != null)
  1114. CloseMenu (false, true);
  1115. CloseMenu ();
  1116. if (LastFocused != null && LastFocused != this)
  1117. selected = -1;
  1118. }
  1119. IsMenuOpen = false;
  1120. openedByHotKey = false;
  1121. openedByAltKey = false;
  1122. }
  1123. View FindDeepestMenu (View view, ref int count)
  1124. {
  1125. count = count > 0 ? count : 0;
  1126. foreach (var menu in view.Subviews) {
  1127. if (menu is Menu) {
  1128. count++;
  1129. return FindDeepestMenu ((Menu)menu, ref count);
  1130. }
  1131. }
  1132. return view;
  1133. }
  1134. internal void PreviousMenu (bool isSubMenu = false)
  1135. {
  1136. switch (isSubMenu) {
  1137. case false:
  1138. if (selected <= 0)
  1139. selected = Menus.Length - 1;
  1140. else
  1141. selected--;
  1142. if (selected > -1)
  1143. CloseMenu (true, false);
  1144. OpenMenu (selected);
  1145. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current, false)) {
  1146. openCurrentMenu.current = 0;
  1147. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  1148. CloseMenu ();
  1149. }
  1150. break;
  1151. }
  1152. break;
  1153. case true:
  1154. if (selectedSub > -1) {
  1155. selectedSub--;
  1156. RemoveSubMenu (selectedSub);
  1157. SetNeedsDisplay ();
  1158. } else
  1159. PreviousMenu ();
  1160. break;
  1161. }
  1162. }
  1163. internal void NextMenu (bool isSubMenu = false)
  1164. {
  1165. switch (isSubMenu) {
  1166. case false:
  1167. if (selected == -1)
  1168. selected = 0;
  1169. else if (selected + 1 == Menus.Length)
  1170. selected = 0;
  1171. else
  1172. selected++;
  1173. if (selected > -1)
  1174. CloseMenu (true);
  1175. OpenMenu (selected);
  1176. SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current);
  1177. break;
  1178. case true:
  1179. if (UseKeysUpDownAsKeysLeftRight) {
  1180. CloseMenu (false, true);
  1181. NextMenu ();
  1182. } else {
  1183. var subMenu = openCurrentMenu.barItems.SubMenu (openCurrentMenu.barItems.Children [openCurrentMenu.current]);
  1184. if ((selectedSub == -1 || openSubMenu == null || openSubMenu?.Count == selectedSub) && subMenu == null) {
  1185. if (openSubMenu != null)
  1186. CloseMenu (false, true);
  1187. NextMenu ();
  1188. } else if (subMenu != null ||
  1189. !openCurrentMenu.barItems.Children [openCurrentMenu.current].IsFromSubMenu)
  1190. selectedSub++;
  1191. else
  1192. return;
  1193. SetNeedsDisplay ();
  1194. openCurrentMenu.CheckSubMenu ();
  1195. }
  1196. break;
  1197. }
  1198. }
  1199. bool openedByHotKey;
  1200. internal bool FindAndOpenMenuByHotkey (KeyEvent kb)
  1201. {
  1202. //int pos = 0;
  1203. var c = ((uint)kb.Key & (uint)Key.CharMask);
  1204. for (int i = 0; i < Menus.Length; i++) {
  1205. // TODO: this code is duplicated, hotkey should be part of the MenuBarItem
  1206. var mi = Menus [i];
  1207. int p = mi.Title.IndexOf ('_');
  1208. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1209. if (Char.ToUpperInvariant ((char)mi.Title [p + 1]) == c) {
  1210. ProcessMenu (i, mi);
  1211. return true;
  1212. }
  1213. }
  1214. }
  1215. return false;
  1216. }
  1217. internal bool FindAndOpenMenuByShortcut (KeyEvent kb, MenuItem [] children = null)
  1218. {
  1219. if (children == null) {
  1220. children = Menus;
  1221. }
  1222. var key = kb.KeyValue;
  1223. var keys = ShortcutHelper.GetModifiersKey (kb);
  1224. key |= (int)keys;
  1225. for (int i = 0; i < children.Length; i++) {
  1226. var mi = children [i];
  1227. if (mi == null) {
  1228. continue;
  1229. }
  1230. if ((!(mi is MenuBarItem mbiTopLevel) || mbiTopLevel.IsTopLevel) && mi.Shortcut != Key.Null && mi.Shortcut == (Key)key) {
  1231. var action = mi.Action;
  1232. if (action != null) {
  1233. Application.MainLoop.AddIdle (() => {
  1234. action ();
  1235. return false;
  1236. });
  1237. }
  1238. return true;
  1239. }
  1240. if (mi is MenuBarItem menuBarItem && !menuBarItem.IsTopLevel && FindAndOpenMenuByShortcut (kb, menuBarItem.Children)) {
  1241. return true;
  1242. }
  1243. }
  1244. return false;
  1245. }
  1246. private void ProcessMenu (int i, MenuBarItem mi)
  1247. {
  1248. if (mi.IsTopLevel) {
  1249. var menu = new Menu (this, i, 0, mi);
  1250. menu.Run (mi.Action);
  1251. menu.Dispose ();
  1252. } else {
  1253. openedByHotKey = true;
  1254. Application.GrabMouse (this);
  1255. selected = i;
  1256. OpenMenu (i);
  1257. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  1258. CloseMenu ();
  1259. }
  1260. openCurrentMenu.CheckSubMenu ();
  1261. }
  1262. }
  1263. ///<inheritdoc/>
  1264. public override bool ProcessHotKey (KeyEvent kb)
  1265. {
  1266. if (kb.Key == Key.F9) {
  1267. if (!IsMenuOpen)
  1268. OpenMenu ();
  1269. else
  1270. CloseAllMenus ();
  1271. return true;
  1272. }
  1273. // To ncurses simulate a AltMask key pressing Alt+Space because
  1274. // it can�t detect an alone special key down was pressed.
  1275. if (kb.IsAlt && kb.Key == Key.AltMask && openMenu == null) {
  1276. OnKeyDown (kb);
  1277. OnKeyUp (kb);
  1278. return true;
  1279. } else if (kb.IsAlt && !kb.IsCtrl && !kb.IsShift) {
  1280. if (FindAndOpenMenuByHotkey (kb)) return true;
  1281. }
  1282. //var kc = kb.KeyValue;
  1283. return base.ProcessHotKey (kb);
  1284. }
  1285. ///<inheritdoc/>
  1286. public override bool ProcessKey (KeyEvent kb)
  1287. {
  1288. switch (kb.Key) {
  1289. case Key.CursorLeft:
  1290. selected--;
  1291. if (selected < 0)
  1292. selected = Menus.Length - 1;
  1293. break;
  1294. case Key.CursorRight:
  1295. selected = (selected + 1) % Menus.Length;
  1296. break;
  1297. case Key.Esc:
  1298. case Key.C | Key.CtrlMask:
  1299. //TODO: Running = false;
  1300. CloseMenu ();
  1301. if (openedByAltKey) {
  1302. openedByAltKey = false;
  1303. LastFocused?.SetFocus ();
  1304. }
  1305. break;
  1306. case Key.CursorDown:
  1307. case Key.Enter:
  1308. if (selected > -1) {
  1309. ProcessMenu (selected, Menus [selected]);
  1310. }
  1311. break;
  1312. default:
  1313. var key = kb.KeyValue;
  1314. if ((key >= 'a' && key <= 'z') || (key >= 'A' && key <= 'Z') || (key >= '0' && key <= '9')) {
  1315. char c = Char.ToUpper ((char)key);
  1316. if (selected == -1 || Menus [selected].IsTopLevel)
  1317. return false;
  1318. foreach (var mi in Menus [selected].Children) {
  1319. if (mi == null)
  1320. continue;
  1321. int p = mi.Title.IndexOf ('_');
  1322. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1323. if (mi.Title [p + 1] == c) {
  1324. Selected (mi);
  1325. return true;
  1326. }
  1327. }
  1328. }
  1329. }
  1330. return false;
  1331. }
  1332. SetNeedsDisplay ();
  1333. return true;
  1334. }
  1335. ///<inheritdoc/>
  1336. public override bool ProcessColdKey (KeyEvent kb)
  1337. {
  1338. return FindAndOpenMenuByShortcut (kb);
  1339. }
  1340. ///<inheritdoc/>
  1341. public override bool MouseEvent (MouseEvent me)
  1342. {
  1343. if (!handled && !HandleGrabView (me, this)) {
  1344. return false;
  1345. }
  1346. handled = false;
  1347. if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked || me.Flags == MouseFlags.Button1Clicked ||
  1348. (me.Flags == MouseFlags.ReportMousePosition && selected > -1) ||
  1349. (me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && selected > -1)) {
  1350. int pos = 1;
  1351. int cx = me.X;
  1352. for (int i = 0; i < Menus.Length; i++) {
  1353. if (cx >= pos && cx < pos + 1 + Menus [i].TitleLength + Menus [i].Help.RuneCount + 2) {
  1354. if (me.Flags == MouseFlags.Button1Clicked) {
  1355. if (Menus [i].IsTopLevel) {
  1356. var menu = new Menu (this, i, 0, Menus [i]);
  1357. menu.Run (Menus [i].Action);
  1358. menu.Dispose ();
  1359. }
  1360. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked) {
  1361. if (IsMenuOpen && !Menus [i].IsTopLevel) {
  1362. CloseAllMenus ();
  1363. } else if (!Menus [i].IsTopLevel) {
  1364. Activate (i);
  1365. }
  1366. } else if (selected != i && selected > -1 && (me.Flags == MouseFlags.ReportMousePosition ||
  1367. me.Flags == MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)) {
  1368. if (IsMenuOpen) {
  1369. CloseMenu (true, false);
  1370. Activate (i);
  1371. }
  1372. } else {
  1373. if (IsMenuOpen)
  1374. Activate (i);
  1375. }
  1376. return true;
  1377. }
  1378. pos += 1 + Menus [i].TitleLength + 2;
  1379. }
  1380. }
  1381. return false;
  1382. }
  1383. internal bool handled;
  1384. internal bool HandleGrabView (MouseEvent me, View current)
  1385. {
  1386. if (Application.mouseGrabView != null) {
  1387. if (me.View is MenuBar || me.View is Menu) {
  1388. if (me.View != current) {
  1389. Application.UngrabMouse ();
  1390. var v = me.View;
  1391. Application.GrabMouse (v);
  1392. var newxy = v.ScreenToView (me.X, me.Y);
  1393. var nme = new MouseEvent () {
  1394. X = newxy.X,
  1395. Y = newxy.Y,
  1396. Flags = me.Flags,
  1397. OfX = me.X - newxy.X,
  1398. OfY = me.Y - newxy.Y,
  1399. View = v
  1400. };
  1401. v.MouseEvent (nme);
  1402. return false;
  1403. }
  1404. } else if (!(me.View is MenuBar || me.View is Menu) && (me.Flags.HasFlag (MouseFlags.Button1Clicked) ||
  1405. me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked)) {
  1406. Application.UngrabMouse ();
  1407. CloseAllMenus ();
  1408. handled = false;
  1409. return false;
  1410. } else {
  1411. handled = false;
  1412. return false;
  1413. }
  1414. } else if (!IsMenuOpen && (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked || me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))) {
  1415. Application.GrabMouse (current);
  1416. } else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu)) {
  1417. Application.GrabMouse (me.View);
  1418. } else {
  1419. handled = false;
  1420. return false;
  1421. }
  1422. //if (me.View != this && me.Flags != MouseFlags.Button1Pressed)
  1423. // return true;
  1424. //else if (me.View != this && me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1425. // Application.UngrabMouse ();
  1426. // host.CloseAllMenus ();
  1427. // return true;
  1428. //}
  1429. //if (!(me.View is MenuBar) && !(me.View is Menu) && me.Flags != MouseFlags.Button1Pressed))
  1430. // return false;
  1431. //if (Application.mouseGrabView != null) {
  1432. // if (me.View is MenuBar || me.View is Menu) {
  1433. // me.X -= me.OfX;
  1434. // me.Y -= me.OfY;
  1435. // me.View.MouseEvent (me);
  1436. // return true;
  1437. // } else if (!(me.View is MenuBar || me.View is Menu) && me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1438. // Application.UngrabMouse ();
  1439. // CloseAllMenus ();
  1440. // }
  1441. //} else if (!isMenuClosed && selected == -1 && me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1442. // Application.GrabMouse (this);
  1443. // return true;
  1444. //}
  1445. //if (Application.mouseGrabView != null) {
  1446. // if (Application.mouseGrabView == me.View && me.View == current) {
  1447. // me.X -= me.OfX;
  1448. // me.Y -= me.OfY;
  1449. // } else if (me.View != current && me.View is MenuBar && me.View is Menu) {
  1450. // Application.UngrabMouse ();
  1451. // Application.GrabMouse (me.View);
  1452. // } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1453. // Application.UngrabMouse ();
  1454. // CloseMenu ();
  1455. // }
  1456. //} else if ((!isMenuClosed && selected > -1)) {
  1457. // Application.GrabMouse (current);
  1458. //}
  1459. handled = true;
  1460. return true;
  1461. }
  1462. }
  1463. }