Menu.cs 48 KB

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