Menu.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277
  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. /// A <see cref="MenuItemCheckType"/> has a title, an associated help text, and an action to execute on activation.
  17. /// </summary>
  18. public class MenuItem {
  19. /// <summary>
  20. /// Initializes a new instance of <see cref="MenuItem"/>
  21. /// </summary>
  22. public MenuItem ()
  23. {
  24. Title = "";
  25. Help = "";
  26. }
  27. /// <summary>
  28. /// Initializes a new instance of <see cref="MenuItem"/>.
  29. /// </summary>
  30. /// <param name="title">Title for the menu item.</param>
  31. /// <param name="help">Help text to display.</param>
  32. /// <param name="action">Action to invoke when the menu item is activated.</param>
  33. /// <param name="canExecute">Function to determine if the action can currently be executred.</param>
  34. public MenuItem (ustring title, string help, Action action, Func<bool> canExecute = null)
  35. {
  36. Title = title ?? "";
  37. Help = help ?? "";
  38. Action = action;
  39. CanExecute = canExecute;
  40. bool nextIsHot = false;
  41. foreach (var x in Title) {
  42. if (x == '_')
  43. nextIsHot = true;
  44. else {
  45. if (nextIsHot) {
  46. HotKey = Char.ToUpper ((char)x);
  47. break;
  48. }
  49. nextIsHot = false;
  50. }
  51. }
  52. }
  53. /// <summary>
  54. /// Initializes a new instance of <see cref="MenuItem"/>
  55. /// </summary>
  56. /// <param name="title">Title for the menu item.</param>
  57. /// <param name="subMenu">The menu sub-menu.</param>
  58. public MenuItem (ustring title, MenuBarItem subMenu) : this (title, "", null)
  59. {
  60. SubMenu = subMenu;
  61. IsFromSubMenu = true;
  62. }
  63. /// <summary>
  64. /// The HotKey is used when the menu is active, the shortcut can be triggered when the menu is not active.
  65. /// For example HotKey would be "N" when the File Menu is open (assuming there is a "_New" entry
  66. /// if the ShortCut is set to "Control-N", this would be a global hotkey that would trigger as well
  67. /// </summary>
  68. public Rune HotKey;
  69. /// <summary>
  70. /// This is the global setting that can be used as a global shortcut to invoke the action on the menu.
  71. /// </summary>
  72. public Key ShortCut;
  73. /// <summary>
  74. /// Gets or sets the title.
  75. /// </summary>
  76. /// <value>The title.</value>
  77. public ustring Title { get; set; }
  78. /// <summary>
  79. /// Gets or sets the help text for the menu item.
  80. /// </summary>
  81. /// <value>The help text.</value>
  82. public ustring Help { get; set; }
  83. /// <summary>
  84. /// Gets or sets the action to be invoked when the menu is triggered
  85. /// </summary>
  86. /// <value>Method to invoke.</value>
  87. public Action Action { get; set; }
  88. /// <summary>
  89. /// Gets or sets the action to be invoked if the menu can be triggered
  90. /// </summary>
  91. /// <value>Function to determine if action is ready to be executed.</value>
  92. public Func<bool> CanExecute { get; set; }
  93. /// <summary>
  94. /// Shortcut to check if the menu item is enabled
  95. /// </summary>
  96. public bool IsEnabled ()
  97. {
  98. return CanExecute == null ? true : CanExecute ();
  99. }
  100. internal int Width => Title.Length + Help.Length + 1 + 2 +
  101. (Checked || CheckType.HasFlag (MenuItemCheckType.Checked) || CheckType.HasFlag (MenuItemCheckType.Radio) ? 2 : 0);
  102. /// <summary>
  103. /// Sets or gets whether the <see cref="MenuItem"/> shows a check indicator or not. See <see cref="MenuItemCheckType"/>.
  104. /// </summary>
  105. public bool Checked { set; get; }
  106. /// <summary>
  107. /// Specifies how a <see cref="MenuItem"/> shows selection state.
  108. /// </summary>
  109. [Flags]
  110. public enum MenuItemCheckType : uint {
  111. /// <summary>
  112. /// The menu item will be shown normally, with no check indicator.
  113. /// </summary>
  114. NoCheck = 0b_0000_0000,
  115. /// <summary>
  116. /// The menu item will indicate checked/un-checked state (see <see cref="Checked"/>.
  117. /// </summary>
  118. Checked = 0b_0000_0001,
  119. /// <summary>
  120. /// The menu item is part of a menu radio group (see <see cref="Checked"/> and will indicate selected state.
  121. /// </summary>
  122. Radio = 0b_0000_0010,
  123. };
  124. /// <summary>
  125. /// Sets or gets the type selection indicator the menu item will be displayed with.
  126. /// </summary>
  127. public MenuItemCheckType CheckType { get; set; }
  128. /// <summary>
  129. /// Gets or sets the parent for this <see cref="MenuItem"/>
  130. /// </summary>
  131. /// <value>The parent.</value>
  132. internal MenuBarItem SubMenu { get; set; }
  133. internal bool IsFromSubMenu { get; set; }
  134. /// <summary>
  135. /// Merely a debugging aid to see the interaction with main
  136. /// </summary>
  137. public MenuItem GetMenuItem ()
  138. {
  139. return this;
  140. }
  141. /// <summary>
  142. /// Merely a debugging aid to see the interaction with main
  143. /// </summary>
  144. public bool GetMenuBarItem ()
  145. {
  146. return IsFromSubMenu;
  147. }
  148. }
  149. /// <summary>
  150. /// A <see cref="MenuBarItem"/> contains <see cref="MenuBarItem"/>s or <see cref="MenuItem"/>s.
  151. /// </summary>
  152. public class MenuBarItem : MenuItem {
  153. /// <summary>
  154. /// Initializes a new <see cref="MenuBarItem"/> as a <see cref="MenuItem"/>.
  155. /// </summary>
  156. /// <param name="title">Title for the menu item.</param>
  157. /// <param name="help">Help text to display.</param>
  158. /// <param name="action">Action to invoke when the menu item is activated.</param>
  159. /// <param name="canExecute">Function to determine if the action can currently be executred.</param>
  160. public MenuBarItem (ustring title, string help, Action action, Func<bool> canExecute = null) : base (title, help, action, canExecute)
  161. {
  162. SetTitle (title ?? "");
  163. Children = null;
  164. }
  165. /// <summary>
  166. /// Initializes a new <see cref="MenuBarItem"/>.
  167. /// </summary>
  168. /// <param name="title">Title for the menu item.</param>
  169. /// <param name="children">The items in the current menu.</param>
  170. public MenuBarItem (ustring title, MenuItem [] children)
  171. {
  172. if (children == null)
  173. throw new ArgumentNullException (nameof (children), "The parameter cannot be null. Use an empty array instead.");
  174. SetTitle (title ?? "");
  175. Children = children;
  176. }
  177. /// <summary>
  178. /// Initializes a new <see cref="MenuBarItem"/>.
  179. /// </summary>
  180. /// <param name="children">The items in the current menu.</param>
  181. public MenuBarItem (MenuItem [] children) : this (new string (' ', GetMaxTitleLength (children)), children) { }
  182. /// <summary>
  183. /// Initializes a new <see cref="MenuBarItem"/>.
  184. /// </summary>
  185. public MenuBarItem () : this (children: new MenuItem [] { }) { }
  186. static int GetMaxTitleLength (MenuItem [] children)
  187. {
  188. int maxLength = 0;
  189. foreach (var item in children) {
  190. int len = GetMenuBarItemLength (item.Title);
  191. if (len > maxLength)
  192. maxLength = len;
  193. item.IsFromSubMenu = true;
  194. }
  195. return maxLength;
  196. }
  197. void SetTitle (ustring title)
  198. {
  199. if (title == null)
  200. title = "";
  201. Title = title;
  202. TitleLength = GetMenuBarItemLength (Title);
  203. }
  204. static int GetMenuBarItemLength (ustring title)
  205. {
  206. int len = 0;
  207. foreach (var ch in title) {
  208. if (ch == '_')
  209. continue;
  210. len++;
  211. }
  212. return len;
  213. }
  214. ///// <summary>
  215. ///// Gets or sets the title to display.
  216. ///// </summary>
  217. ///// <value>The title.</value>
  218. //public ustring Title { get; set; }
  219. /// <summary>
  220. /// Gets or sets an array of <see cref="MenuItem"/> objects that are the children of this <see cref="MenuBarItem"/>
  221. /// </summary>
  222. /// <value>The children.</value>
  223. public MenuItem [] Children { get; set; }
  224. internal int TitleLength { get; private set; }
  225. internal bool IsTopLevel { get => (Children == null || Children.Length == 0); }
  226. }
  227. class Menu : View {
  228. internal MenuBarItem barItems;
  229. MenuBar host;
  230. internal int current;
  231. internal View previousSubFocused;
  232. static Rect MakeFrame (int x, int y, MenuItem [] items)
  233. {
  234. if (items == null || items.Length == 0) {
  235. return new Rect ();
  236. }
  237. int maxW = items.Max (z => z?.Width) ?? 0;
  238. return new Rect (x, y, maxW + 2, items.Length + 2);
  239. }
  240. public Menu (MenuBar host, int x, int y, MenuBarItem barItems) : base (MakeFrame (x, y, barItems.Children))
  241. {
  242. this.barItems = barItems;
  243. this.host = host;
  244. if (barItems.IsTopLevel) {
  245. // This is a standalone MenuItem on a MenuBar
  246. ColorScheme = Colors.Menu;
  247. CanFocus = true;
  248. } else {
  249. current = -1;
  250. for (int i = 0; i < barItems.Children.Length; i++) {
  251. if (barItems.Children [i] != null) {
  252. current = i;
  253. break;
  254. }
  255. }
  256. ColorScheme = Colors.Menu;
  257. CanFocus = true;
  258. WantMousePositionReports = host.WantMousePositionReports;
  259. }
  260. }
  261. internal Attribute DetermineColorSchemeFor (MenuItem item, int index)
  262. {
  263. if (item != null) {
  264. if (index == current) return ColorScheme.Focus;
  265. if (!item.IsEnabled ()) return ColorScheme.Disabled;
  266. }
  267. return ColorScheme.Normal;
  268. }
  269. public override void Redraw (Rect bounds)
  270. {
  271. Driver.SetAttribute (ColorScheme.Normal);
  272. DrawFrame (bounds, padding: 0, fill: true);
  273. for (int i = 0; i < barItems.Children.Length; i++) {
  274. var item = barItems.Children [i];
  275. Driver.SetAttribute (item == null ? ColorScheme.Normal : i == current ? ColorScheme.Focus : ColorScheme.Normal);
  276. if (item == null) {
  277. Move (0, i + 1);
  278. Driver.AddRune (Driver.LeftTee);
  279. } else
  280. Move (1, i + 1);
  281. Driver.SetAttribute (DetermineColorSchemeFor (item, i));
  282. for (int p = 0; p < Frame.Width - 2; p++)
  283. if (item == null)
  284. Driver.AddRune (Driver.HLine);
  285. else if (p == Frame.Width - 3 && barItems.Children [i].SubMenu != null)
  286. Driver.AddRune ('>');
  287. else
  288. Driver.AddRune (' ');
  289. if (item == null) {
  290. Move (Frame.Right - 1, i + 1);
  291. Driver.AddRune (Driver.RightTee);
  292. continue;
  293. }
  294. ustring textToDraw;
  295. var checkChar = (char)0x25cf;
  296. var uncheckedChar = (char)0x25cc;
  297. if (item.CheckType.HasFlag (MenuItem.MenuItemCheckType.Checked)) {
  298. checkChar = (char)0x221a;
  299. uncheckedChar = ' ';
  300. }
  301. // Support Checked even though CHeckType wasn't set
  302. if (item.Checked) {
  303. textToDraw = checkChar + " " + item.Title;
  304. } else if (item.CheckType.HasFlag (MenuItem.MenuItemCheckType.Checked) ||
  305. item.CheckType.HasFlag (MenuItem.MenuItemCheckType.Radio)) {
  306. textToDraw = uncheckedChar + " " + item.Title;
  307. } else {
  308. textToDraw = item.Title;
  309. }
  310. Move (2, i + 1);
  311. if (!item.IsEnabled ())
  312. DrawHotString (textToDraw, ColorScheme.Disabled, ColorScheme.Disabled);
  313. else
  314. DrawHotString (textToDraw,
  315. i == current ? ColorScheme.HotFocus : ColorScheme.HotNormal,
  316. i == current ? ColorScheme.Focus : ColorScheme.Normal);
  317. // The help string
  318. var l = item.Help.Length;
  319. Move (Frame.Width - l - 2, 1 + i);
  320. Driver.AddStr (item.Help);
  321. }
  322. PositionCursor ();
  323. }
  324. public override void PositionCursor ()
  325. {
  326. if (host == null || host.IsMenuOpen)
  327. if (barItems.IsTopLevel) {
  328. host.PositionCursor ();
  329. } else
  330. Move (2, 1 + current);
  331. else
  332. host.PositionCursor ();
  333. }
  334. public void Run (Action action)
  335. {
  336. if (action == null)
  337. return;
  338. Application.UngrabMouse ();
  339. host.CloseAllMenus ();
  340. Application.Refresh ();
  341. Application.MainLoop.AddIdle (() => {
  342. action ();
  343. return false;
  344. });
  345. }
  346. public override bool OnKeyDown (KeyEvent keyEvent)
  347. {
  348. if (keyEvent.IsAlt) {
  349. host.CloseAllMenus ();
  350. return true;
  351. }
  352. return false;
  353. }
  354. public override bool ProcessHotKey (KeyEvent keyEvent)
  355. {
  356. // To ncurses simulate a AltMask key pressing Alt+Space because
  357. // it can�t detect an alone special key down was pressed.
  358. if (keyEvent.IsAlt && keyEvent.Key == Key.AltMask) {
  359. OnKeyDown (keyEvent);
  360. return true;
  361. }
  362. return false;
  363. }
  364. public override bool ProcessKey (KeyEvent kb)
  365. {
  366. bool disabled;
  367. switch (kb.Key) {
  368. case Key.CursorUp:
  369. if (barItems.IsTopLevel || current == -1)
  370. break;
  371. do {
  372. disabled = false;
  373. current--;
  374. if (host.UseKeysUpDownAsKeysLeftRight) {
  375. if (current == -1 && barItems.Children [current + 1].IsFromSubMenu && host.selectedSub > -1) {
  376. current++;
  377. host.PreviousMenu (true);
  378. break;
  379. }
  380. }
  381. if (current < 0)
  382. current = barItems.Children.Length - 1;
  383. var item = barItems.Children [current];
  384. if (item == null || !item.IsEnabled ()) disabled = true;
  385. } while (barItems.Children [current] == null || disabled);
  386. SetNeedsDisplay ();
  387. break;
  388. case Key.CursorDown:
  389. if (barItems.IsTopLevel) {
  390. break;
  391. }
  392. do {
  393. current++;
  394. disabled = false;
  395. if (current == barItems.Children.Length)
  396. current = 0;
  397. var item = barItems.Children [current];
  398. if (item == null || !item.IsEnabled ()) disabled = true;
  399. if (host.UseKeysUpDownAsKeysLeftRight && barItems.Children [current]?.SubMenu != null &&
  400. !disabled && host.IsMenuOpen) {
  401. CheckSubMenu ();
  402. break;
  403. }
  404. if (!host.IsMenuOpen)
  405. host.OpenMenu (host.selected);
  406. } while (barItems.Children [current] == null || disabled);
  407. SetNeedsDisplay ();
  408. break;
  409. case Key.CursorLeft:
  410. host.PreviousMenu (true);
  411. break;
  412. case Key.CursorRight:
  413. host.NextMenu (barItems.IsTopLevel || barItems.Children [current].IsFromSubMenu ? true : false);
  414. break;
  415. case Key.Esc:
  416. Application.UngrabMouse ();
  417. host.CloseAllMenus ();
  418. break;
  419. case Key.Enter:
  420. if (barItems.IsTopLevel) {
  421. Run (barItems.Action);
  422. } else {
  423. CheckSubMenu ();
  424. Run (barItems.Children [current].Action);
  425. }
  426. break;
  427. default:
  428. // TODO: rune-ify
  429. if (barItems.Children != null && Char.IsLetterOrDigit ((char)kb.KeyValue)) {
  430. var x = Char.ToUpper ((char)kb.KeyValue);
  431. foreach (var item in barItems.Children) {
  432. if (item == null) continue;
  433. if (item.IsEnabled () && item.HotKey == x) {
  434. host.CloseMenu ();
  435. Run (item.Action);
  436. return true;
  437. }
  438. }
  439. }
  440. break;
  441. }
  442. return true;
  443. }
  444. public override bool MouseEvent (MouseEvent me)
  445. {
  446. if (!host.handled && !host.HandleGrabView (me, this)) {
  447. return false;
  448. }
  449. host.handled = false;
  450. bool disabled;
  451. if (me.Flags == MouseFlags.Button1Clicked) {
  452. disabled = false;
  453. if (me.Y < 1)
  454. return true;
  455. var meY = me.Y - 1;
  456. if (meY >= barItems.Children.Length)
  457. return true;
  458. var item = barItems.Children [meY];
  459. if (item == null || !item.IsEnabled ()) disabled = true;
  460. if (item != null && !disabled)
  461. Run (barItems.Children [meY].Action);
  462. return true;
  463. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked ||
  464. me.Flags == MouseFlags.ReportMousePosition ||
  465. me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  466. disabled = false;
  467. if (me.Y < 1)
  468. return true;
  469. if (me.Y - 1 >= barItems.Children.Length)
  470. return true;
  471. var item = barItems.Children [me.Y - 1];
  472. if (item == null || !item.IsEnabled ()) disabled = true;
  473. if (item != null && !disabled)
  474. current = me.Y - 1;
  475. HasFocus = true;
  476. SetNeedsDisplay ();
  477. CheckSubMenu ();
  478. return true;
  479. }
  480. return false;
  481. }
  482. internal void CheckSubMenu ()
  483. {
  484. if (barItems.Children [current] == null)
  485. return;
  486. var subMenu = barItems.Children [current].SubMenu;
  487. if (subMenu != null) {
  488. int pos = -1;
  489. if (host.openSubMenu != null)
  490. pos = host.openSubMenu.FindIndex (o => o?.barItems == subMenu);
  491. host.Activate (host.selected, pos, subMenu);
  492. } else if (host.openSubMenu != null && !barItems.Children [current].IsFromSubMenu)
  493. host.CloseMenu (false, true);
  494. }
  495. int GetSubMenuIndex (MenuBarItem subMenu)
  496. {
  497. int pos = -1;
  498. if (this != null && Subviews.Count > 0) {
  499. Menu v = null;
  500. foreach (var menu in Subviews) {
  501. if (((Menu)menu).barItems == subMenu)
  502. v = (Menu)menu;
  503. }
  504. if (v != null)
  505. pos = Subviews.IndexOf (v);
  506. }
  507. return pos;
  508. }
  509. }
  510. /// <summary>
  511. /// The MenuBar provides a menu for Terminal.Gui applications.
  512. /// </summary>
  513. /// <remarks>
  514. /// <para>
  515. /// The <see cref="MenuBar"/> appears on the first row of the terminal.
  516. /// </para>
  517. /// <para>
  518. /// The <see cref="MenuBar"/> provides global hotkeys for the application.
  519. /// </para>
  520. /// </remarks>
  521. public class MenuBar : View {
  522. /// <summary>
  523. /// Gets or sets the array of <see cref="MenuBarItem"/>s for the menu. Only set this when the <see cref="MenuBar"/> is vislble.
  524. /// </summary>
  525. /// <value>The menu array.</value>
  526. public MenuBarItem [] Menus { get; set; }
  527. internal int selected;
  528. internal int selectedSub;
  529. Action action;
  530. /// <summary>
  531. /// Used for change the navigation key style.
  532. /// </summary>
  533. public bool UseKeysUpDownAsKeysLeftRight { get; set; } = true;
  534. /// <summary>
  535. /// Initializes a new instance of the <see cref="MenuBar"/>.
  536. /// </summary>
  537. public MenuBar () : this (new MenuBarItem [] { }) { }
  538. /// <summary>
  539. /// Initializes a new instance of the <see cref="MenuBar"/> class with the specified set of toplevel menu items.
  540. /// </summary>
  541. /// <param name="menus">Individual menu items; a null item will result in a separator being drawn.</param>
  542. public MenuBar (MenuBarItem [] menus) : base ()
  543. {
  544. X = 0;
  545. Y = 0;
  546. Width = Dim.Fill ();
  547. Height = 1;
  548. Menus = menus;
  549. //CanFocus = true;
  550. selected = -1;
  551. selectedSub = -1;
  552. ColorScheme = Colors.Menu;
  553. WantMousePositionReports = true;
  554. IsMenuOpen = false;
  555. }
  556. bool openedByAltKey;
  557. ///<inheritdoc/>
  558. public override bool OnKeyDown (KeyEvent keyEvent)
  559. {
  560. if (keyEvent.IsAlt) {
  561. openedByAltKey = true;
  562. SetNeedsDisplay ();
  563. openedByHotKey = false;
  564. }
  565. return false;
  566. }
  567. ///<inheritdoc/>
  568. public override bool OnKeyUp (KeyEvent keyEvent)
  569. {
  570. if (keyEvent.IsAlt) {
  571. // User pressed Alt - this may be a precursor to a menu accelerator (e.g. Alt-F)
  572. if (!keyEvent.IsCtrl && openedByAltKey && !IsMenuOpen && openMenu == null && ((uint)keyEvent.Key & (uint)Key.CharMask) == 0) {
  573. // There's no open menu, the first menu item should be highlight.
  574. // The right way to do this is to SetFocus(MenuBar), but for some reason
  575. // that faults.
  576. //Activate (0);
  577. //StartMenu ();
  578. IsMenuOpen = true;
  579. selected = 0;
  580. CanFocus = true;
  581. lastFocused = SuperView.MostFocused;
  582. SuperView.SetFocus (this);
  583. SetNeedsDisplay ();
  584. Application.GrabMouse (this);
  585. } else if (!openedByHotKey) {
  586. // There's an open menu. If this Alt key-up is a pre-cursor to an accelerator
  587. // we don't want to close the menu because it'll flash.
  588. // How to deal with that?
  589. if (openMenu != null)
  590. CloseAllMenus ();
  591. openedByAltKey = false;
  592. IsMenuOpen = false;
  593. selected = -1;
  594. CanFocus = false;
  595. if (lastFocused != null)
  596. SuperView?.SetFocus (lastFocused);
  597. SetNeedsDisplay ();
  598. Application.UngrabMouse ();
  599. }
  600. return true;
  601. }
  602. return false;
  603. }
  604. ///<inheritdoc/>
  605. public override void Redraw (Rect bounds)
  606. {
  607. Move (0, 0);
  608. Driver.SetAttribute (Colors.Menu.Normal);
  609. for (int i = 0; i < Frame.Width; i++)
  610. Driver.AddRune (' ');
  611. Move (1, 0);
  612. int pos = 1;
  613. for (int i = 0; i < Menus.Length; i++) {
  614. var menu = Menus [i];
  615. Move (pos, 0);
  616. Attribute hotColor, normalColor;
  617. if (i == selected) {
  618. hotColor = i == selected ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  619. normalColor = i == selected ? ColorScheme.Focus : ColorScheme.Normal;
  620. } else if (openedByAltKey) {
  621. hotColor = ColorScheme.HotNormal;
  622. normalColor = ColorScheme.Normal;
  623. } else {
  624. hotColor = ColorScheme.Normal;
  625. normalColor = ColorScheme.Normal;
  626. }
  627. DrawHotString ($" {menu.Title} ", hotColor, normalColor);
  628. pos += 1 + menu.TitleLength + 2;
  629. }
  630. PositionCursor ();
  631. }
  632. ///<inheritdoc/>
  633. public override void PositionCursor ()
  634. {
  635. int pos = 0;
  636. for (int i = 0; i < Menus.Length; i++) {
  637. if (i == selected) {
  638. pos++;
  639. if (IsMenuOpen)
  640. Move (pos + 1, 0);
  641. else
  642. Move (pos + 1, 0);
  643. return;
  644. } else {
  645. if (IsMenuOpen)
  646. pos += 1 + Menus [i].TitleLength + 2;
  647. else
  648. pos += 2 + Menus [i].TitleLength + 1;
  649. }
  650. }
  651. //Move (0, 0);
  652. }
  653. void Selected (MenuItem item)
  654. {
  655. // TODO: Running = false;
  656. action = item.Action;
  657. }
  658. /// <summary>
  659. /// Raised as a menu is opening.
  660. /// </summary>
  661. public Action MenuOpening;
  662. /// <summary>
  663. /// Raised when a menu is closing.
  664. /// </summary>
  665. public Action MenuClosing;
  666. internal Menu openMenu;
  667. Menu openCurrentMenu;
  668. internal List<Menu> openSubMenu;
  669. View previousFocused;
  670. internal bool isMenuOpening;
  671. internal bool isMenuClosing;
  672. /// <summary>
  673. /// True if the menu is open; otherwise false.
  674. /// </summary>
  675. public bool IsMenuOpen { get; protected set; }
  676. /// <summary>
  677. /// Virtual method that will invoke the <see cref="MenuOpening"/>
  678. /// </summary>
  679. public virtual void OnMenuOpening ()
  680. {
  681. MenuOpening?.Invoke ();
  682. }
  683. /// <summary>
  684. /// Virtual method that will invoke the <see cref="MenuClosing"/>
  685. /// </summary>
  686. public virtual void OnMenuClosing ()
  687. {
  688. MenuClosing?.Invoke ();
  689. }
  690. View lastFocused;
  691. /// <summary>
  692. /// Get the lasted focused view before open the menu.
  693. /// </summary>
  694. public View LastFocused { get; private set; }
  695. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem subMenu = null)
  696. {
  697. isMenuOpening = true;
  698. OnMenuOpening ();
  699. int pos = 0;
  700. switch (subMenu) {
  701. case null:
  702. lastFocused = lastFocused ?? SuperView.MostFocused;
  703. if (openSubMenu != null)
  704. CloseMenu (false, true);
  705. if (openMenu != null)
  706. SuperView.Remove (openMenu);
  707. for (int i = 0; i < index; i++)
  708. pos += Menus [i].Title.Length + 2;
  709. openMenu = new Menu (this, pos, 1, Menus [index]);
  710. openCurrentMenu = openMenu;
  711. openCurrentMenu.previousSubFocused = openMenu;
  712. SuperView.Add (openMenu);
  713. SuperView.SetFocus (openMenu);
  714. break;
  715. default:
  716. if (openSubMenu == null)
  717. openSubMenu = new List<Menu> ();
  718. if (sIndex > -1) {
  719. RemoveSubMenu (sIndex);
  720. } else {
  721. var last = openSubMenu.Count > 0 ? openSubMenu.Last () : openMenu;
  722. openCurrentMenu = new Menu (this, last.Frame.Left + last.Frame.Width, last.Frame.Top + 1 + last.current, subMenu);
  723. openCurrentMenu.previousSubFocused = last.previousSubFocused;
  724. openSubMenu.Add (openCurrentMenu);
  725. SuperView.Add (openCurrentMenu);
  726. }
  727. selectedSub = openSubMenu.Count - 1;
  728. SuperView?.SetFocus (openCurrentMenu);
  729. break;
  730. }
  731. isMenuOpening = false;
  732. IsMenuOpen = true;
  733. }
  734. /// <summary>
  735. /// Opens the current Menu programatically.
  736. /// </summary>
  737. public void OpenMenu ()
  738. {
  739. if (openMenu != null)
  740. return;
  741. selected = 0;
  742. SetNeedsDisplay ();
  743. previousFocused = SuperView.Focused;
  744. OpenMenu (selected);
  745. Application.GrabMouse (this);
  746. }
  747. // Activates the menu, handles either first focus, or activating an entry when it was already active
  748. // For mouse events.
  749. internal void Activate (int idx, int sIdx = -1, MenuBarItem subMenu = null)
  750. {
  751. selected = idx;
  752. selectedSub = sIdx;
  753. if (openMenu == null)
  754. previousFocused = SuperView.Focused;
  755. OpenMenu (idx, sIdx, subMenu);
  756. SetNeedsDisplay ();
  757. }
  758. /// <summary>
  759. /// Closes the current Menu programatically, if open.
  760. /// </summary>
  761. public void CloseMenu ()
  762. {
  763. CloseMenu (false, false);
  764. }
  765. internal void CloseMenu (bool reopen = false, bool isSubMenu = false)
  766. {
  767. isMenuClosing = true;
  768. OnMenuClosing ();
  769. switch (isSubMenu) {
  770. case false:
  771. if (openMenu != null)
  772. SuperView.Remove (openMenu);
  773. SetNeedsDisplay ();
  774. if (previousFocused != null && openMenu != null && previousFocused.ToString () != openCurrentMenu.ToString ())
  775. previousFocused?.SuperView?.SetFocus (previousFocused);
  776. openMenu = null;
  777. if (lastFocused is Menu) {
  778. lastFocused = null;
  779. }
  780. LastFocused = lastFocused;
  781. lastFocused = null;
  782. if (LastFocused != null) {
  783. if (!reopen)
  784. selected = -1;
  785. LastFocused.SuperView?.SetFocus (LastFocused);
  786. } else {
  787. SuperView.SetFocus (this);
  788. PositionCursor ();
  789. }
  790. IsMenuOpen = false;
  791. break;
  792. case true:
  793. selectedSub = -1;
  794. SetNeedsDisplay ();
  795. RemoveAllOpensSubMenus ();
  796. openCurrentMenu.previousSubFocused?.SuperView?.SetFocus (openCurrentMenu.previousSubFocused);
  797. openSubMenu = null;
  798. IsMenuOpen = true;
  799. break;
  800. }
  801. isMenuClosing = false;
  802. }
  803. void RemoveSubMenu (int index)
  804. {
  805. if (openSubMenu == null)
  806. return;
  807. for (int i = openSubMenu.Count - 1; i > index; i--) {
  808. isMenuClosing = true;
  809. if (openSubMenu.Count - 1 > 0)
  810. SuperView.SetFocus (openSubMenu [i - 1]);
  811. else
  812. SuperView.SetFocus (openMenu);
  813. if (openSubMenu != null) {
  814. SuperView.Remove (openSubMenu [i]);
  815. openSubMenu.Remove (openSubMenu [i]);
  816. }
  817. RemoveSubMenu (i);
  818. }
  819. if (openSubMenu.Count > 0)
  820. openCurrentMenu = openSubMenu.Last ();
  821. //if (openMenu.Subviews.Count == 0)
  822. // return;
  823. //if (index == 0) {
  824. // //SuperView.SetFocus (previousSubFocused);
  825. // FocusPrev ();
  826. // return;
  827. //}
  828. //for (int i = openMenu.Subviews.Count - 1; i > index; i--) {
  829. // isMenuClosing = true;
  830. // if (openMenu.Subviews.Count - 1 > 0)
  831. // SuperView.SetFocus (openMenu.Subviews [i - 1]);
  832. // else
  833. // SuperView.SetFocus (openMenu);
  834. // if (openMenu != null) {
  835. // Remove (openMenu.Subviews [i]);
  836. // openMenu.Remove (openMenu.Subviews [i]);
  837. // }
  838. // RemoveSubMenu (i);
  839. //}
  840. isMenuClosing = false;
  841. }
  842. internal void RemoveAllOpensSubMenus ()
  843. {
  844. if (openSubMenu != null) {
  845. foreach (var item in openSubMenu) {
  846. SuperView.Remove (item);
  847. }
  848. }
  849. }
  850. internal void CloseAllMenus ()
  851. {
  852. if (!isMenuOpening && !isMenuClosing) {
  853. if (openSubMenu != null)
  854. CloseMenu (false, true);
  855. CloseMenu ();
  856. if (LastFocused != null && LastFocused != this)
  857. selected = -1;
  858. }
  859. IsMenuOpen = false;
  860. openedByHotKey = false;
  861. openedByAltKey = false;
  862. }
  863. View FindDeepestMenu (View view, ref int count)
  864. {
  865. count = count > 0 ? count : 0;
  866. foreach (var menu in view.Subviews) {
  867. if (menu is Menu) {
  868. count++;
  869. return FindDeepestMenu ((Menu)menu, ref count);
  870. }
  871. }
  872. return view;
  873. }
  874. internal void PreviousMenu (bool isSubMenu = false)
  875. {
  876. switch (isSubMenu) {
  877. case false:
  878. if (selected <= 0)
  879. selected = Menus.Length - 1;
  880. else
  881. selected--;
  882. if (selected > -1)
  883. CloseMenu (true, false);
  884. OpenMenu (selected);
  885. break;
  886. case true:
  887. if (selectedSub > -1) {
  888. selectedSub--;
  889. RemoveSubMenu (selectedSub);
  890. SetNeedsDisplay ();
  891. } else
  892. PreviousMenu ();
  893. break;
  894. }
  895. }
  896. internal void NextMenu (bool isSubMenu = false)
  897. {
  898. switch (isSubMenu) {
  899. case false:
  900. if (selected == -1)
  901. selected = 0;
  902. else if (selected + 1 == Menus.Length)
  903. selected = 0;
  904. else
  905. selected++;
  906. if (selected > -1)
  907. CloseMenu (true);
  908. OpenMenu (selected);
  909. break;
  910. case true:
  911. if (UseKeysUpDownAsKeysLeftRight) {
  912. CloseMenu (false, true);
  913. NextMenu ();
  914. } else {
  915. if ((selectedSub == -1 || openSubMenu == null || openSubMenu?.Count == selectedSub) && openCurrentMenu.barItems.Children [openCurrentMenu.current].SubMenu == null) {
  916. if (openSubMenu != null)
  917. CloseMenu (false, true);
  918. NextMenu ();
  919. } else if (openCurrentMenu.barItems.Children [openCurrentMenu.current].SubMenu != null ||
  920. !openCurrentMenu.barItems.Children [openCurrentMenu.current].IsFromSubMenu)
  921. selectedSub++;
  922. else
  923. return;
  924. SetNeedsDisplay ();
  925. openCurrentMenu.CheckSubMenu ();
  926. }
  927. break;
  928. }
  929. }
  930. bool openedByHotKey;
  931. internal bool FindAndOpenMenuByHotkey (KeyEvent kb)
  932. {
  933. //int pos = 0;
  934. var c = ((uint)kb.Key & (uint)Key.CharMask);
  935. for (int i = 0; i < Menus.Length; i++) {
  936. // TODO: this code is duplicated, hotkey should be part of the MenuBarItem
  937. var mi = Menus [i];
  938. int p = mi.Title.IndexOf ('_');
  939. if (p != -1 && p + 1 < mi.Title.Length) {
  940. if (Char.ToUpperInvariant ((char)mi.Title [p + 1]) == c) {
  941. ProcessMenu (i, mi);
  942. return true;
  943. }
  944. }
  945. }
  946. return false;
  947. }
  948. private void ProcessMenu (int i, MenuBarItem mi)
  949. {
  950. if (mi.IsTopLevel) {
  951. var menu = new Menu (this, i, 0, mi);
  952. menu.Run (mi.Action);
  953. } else {
  954. openedByHotKey = true;
  955. Application.GrabMouse (this);
  956. selected = i;
  957. OpenMenu (i);
  958. }
  959. }
  960. ///<inheritdoc/>
  961. public override bool ProcessHotKey (KeyEvent kb)
  962. {
  963. if (kb.Key == Key.F9) {
  964. if (!IsMenuOpen)
  965. OpenMenu ();
  966. else
  967. CloseAllMenus ();
  968. return true;
  969. }
  970. // To ncurses simulate a AltMask key pressing Alt+Space because
  971. // it can�t detect an alone special key down was pressed.
  972. if (kb.IsAlt && kb.Key == Key.AltMask && openMenu == null) {
  973. OnKeyDown (kb);
  974. OnKeyUp (kb);
  975. return true;
  976. } else if (kb.IsAlt) {
  977. if (FindAndOpenMenuByHotkey (kb)) return true;
  978. }
  979. //var kc = kb.KeyValue;
  980. return base.ProcessHotKey (kb);
  981. }
  982. ///<inheritdoc/>
  983. public override bool ProcessKey (KeyEvent kb)
  984. {
  985. switch (kb.Key) {
  986. case Key.CursorLeft:
  987. selected--;
  988. if (selected < 0)
  989. selected = Menus.Length - 1;
  990. break;
  991. case Key.CursorRight:
  992. selected = (selected + 1) % Menus.Length;
  993. break;
  994. case Key.Esc:
  995. case Key.ControlC:
  996. //TODO: Running = false;
  997. CloseMenu ();
  998. if (openedByAltKey) {
  999. openedByAltKey = false;
  1000. LastFocused.SuperView?.SetFocus (LastFocused);
  1001. }
  1002. break;
  1003. case Key.CursorDown:
  1004. case Key.Enter:
  1005. ProcessMenu (selected, Menus [selected]);
  1006. break;
  1007. default:
  1008. var key = kb.KeyValue;
  1009. if ((key >= 'a' && key <= 'z') || (key >= 'A' && key <= 'Z') || (key >= '0' && key <= '9')) {
  1010. char c = Char.ToUpper ((char)key);
  1011. if (selected == -1 || Menus [selected].IsTopLevel)
  1012. return false;
  1013. foreach (var mi in Menus [selected].Children) {
  1014. if (mi == null)
  1015. continue;
  1016. int p = mi.Title.IndexOf ('_');
  1017. if (p != -1 && p + 1 < mi.Title.Length) {
  1018. if (mi.Title [p + 1] == c) {
  1019. Selected (mi);
  1020. return true;
  1021. }
  1022. }
  1023. }
  1024. }
  1025. return false;
  1026. }
  1027. SetNeedsDisplay ();
  1028. return true;
  1029. }
  1030. ///<inheritdoc/>
  1031. public override bool MouseEvent (MouseEvent me)
  1032. {
  1033. if (!handled && !HandleGrabView (me, this)) {
  1034. return false;
  1035. }
  1036. handled = false;
  1037. if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1Clicked ||
  1038. (me.Flags == MouseFlags.ReportMousePosition && selected > -1) ||
  1039. (me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && selected > -1)) {
  1040. int pos = 1;
  1041. int cx = me.X;
  1042. for (int i = 0; i < Menus.Length; i++) {
  1043. if (cx > pos && me.X < pos + 1 + Menus [i].TitleLength) {
  1044. if (me.Flags == MouseFlags.Button1Clicked) {
  1045. if (Menus [i].IsTopLevel) {
  1046. var menu = new Menu (this, i, 0, Menus [i]);
  1047. menu.Run (Menus [i].Action);
  1048. }
  1049. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1050. if (IsMenuOpen) {
  1051. CloseAllMenus ();
  1052. } else {
  1053. Activate (i);
  1054. }
  1055. } else if (selected != i && selected > -1 && (me.Flags == MouseFlags.ReportMousePosition ||
  1056. me.Flags == MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)) {
  1057. if (IsMenuOpen) {
  1058. CloseMenu ();
  1059. Activate (i);
  1060. }
  1061. } else {
  1062. if (IsMenuOpen)
  1063. Activate (i);
  1064. }
  1065. return true;
  1066. }
  1067. pos += 2 + Menus [i].TitleLength + 1;
  1068. }
  1069. }
  1070. return false;
  1071. }
  1072. internal bool handled;
  1073. internal bool HandleGrabView (MouseEvent me, View current)
  1074. {
  1075. if (Application.mouseGrabView != null) {
  1076. if (me.View is MenuBar || me.View is Menu) {
  1077. if (me.View != current) {
  1078. Application.UngrabMouse ();
  1079. Application.GrabMouse (me.View);
  1080. me.View.MouseEvent (me);
  1081. }
  1082. } else if (!(me.View is MenuBar || me.View is Menu) && (me.Flags.HasFlag (MouseFlags.Button1Clicked) ||
  1083. me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked)) {
  1084. Application.UngrabMouse ();
  1085. CloseAllMenus ();
  1086. handled = false;
  1087. return false;
  1088. } else {
  1089. handled = false;
  1090. return false;
  1091. }
  1092. } else if (!IsMenuOpen && (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))) {
  1093. Application.GrabMouse (current);
  1094. } else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu)) {
  1095. Application.GrabMouse (me.View);
  1096. } else {
  1097. handled = false;
  1098. return false;
  1099. }
  1100. //if (me.View != this && me.Flags != MouseFlags.Button1Pressed)
  1101. // return true;
  1102. //else if (me.View != this && me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1103. // Application.UngrabMouse ();
  1104. // host.CloseAllMenus ();
  1105. // return true;
  1106. //}
  1107. //if (!(me.View is MenuBar) && !(me.View is Menu) && me.Flags != MouseFlags.Button1Pressed))
  1108. // return false;
  1109. //if (Application.mouseGrabView != null) {
  1110. // if (me.View is MenuBar || me.View is Menu) {
  1111. // me.X -= me.OfX;
  1112. // me.Y -= me.OfY;
  1113. // me.View.MouseEvent (me);
  1114. // return true;
  1115. // } else if (!(me.View is MenuBar || me.View is Menu) && me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1116. // Application.UngrabMouse ();
  1117. // CloseAllMenus ();
  1118. // }
  1119. //} else if (!isMenuClosed && selected == -1 && me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1120. // Application.GrabMouse (this);
  1121. // return true;
  1122. //}
  1123. //if (Application.mouseGrabView != null) {
  1124. // if (Application.mouseGrabView == me.View && me.View == current) {
  1125. // me.X -= me.OfX;
  1126. // me.Y -= me.OfY;
  1127. // } else if (me.View != current && me.View is MenuBar && me.View is Menu) {
  1128. // Application.UngrabMouse ();
  1129. // Application.GrabMouse (me.View);
  1130. // } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked) {
  1131. // Application.UngrabMouse ();
  1132. // CloseMenu ();
  1133. // }
  1134. //} else if ((!isMenuClosed && selected > -1)) {
  1135. // Application.GrabMouse (current);
  1136. //}
  1137. handled = true;
  1138. return true;
  1139. }
  1140. }
  1141. }