MenuBar.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  1. using System;
  2. using System.Text;
  3. using System.Linq;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. namespace Terminal.Gui;
  7. /// <summary>
  8. /// <see cref="MenuBarItem"/> is a menu item on <see cref="MenuBar"/>.
  9. /// MenuBarItems do not support <see cref="MenuItem.Shortcut"/>.
  10. /// </summary>
  11. public class MenuBarItem : MenuItem {
  12. /// <summary>
  13. /// Initializes a new <see cref="MenuBarItem"/> as a <see cref="MenuItem"/>.
  14. /// </summary>
  15. /// <param name="title">Title for the menu item.</param>
  16. /// <param name="help">Help text to display. Will be displayed next to the Title surrounded by parentheses.</param>
  17. /// <param name="action">Action to invoke when the menu item is activated.</param>
  18. /// <param name="canExecute">Function to determine if the action can currently be executed.</param>
  19. /// <param name="parent">The parent <see cref="MenuItem"/> of this if exist, otherwise is null.</param>
  20. public MenuBarItem (string title, string help, Action action, Func<bool> canExecute = null, MenuItem parent = null) : base (title, help, action, canExecute, parent)
  21. {
  22. Initialize (title, null, null, true);
  23. }
  24. /// <summary>
  25. /// Initializes a new <see cref="MenuBarItem"/>.
  26. /// </summary>
  27. /// <param name="title">Title for the menu item.</param>
  28. /// <param name="children">The items in the current menu.</param>
  29. /// <param name="parent">The parent <see cref="MenuItem"/> of this if exist, otherwise is null.</param>
  30. public MenuBarItem (string title, MenuItem [] children, MenuItem parent = null)
  31. {
  32. Initialize (title, children, parent);
  33. }
  34. /// <summary>
  35. /// Initializes a new <see cref="MenuBarItem"/> with separate list of items.
  36. /// </summary>
  37. /// <param name="title">Title for the menu item.</param>
  38. /// <param name="children">The list of items in the current menu.</param>
  39. /// <param name="parent">The parent <see cref="MenuItem"/> of this if exist, otherwise is null.</param>
  40. public MenuBarItem (string title, List<MenuItem []> children, MenuItem parent = null)
  41. {
  42. Initialize (title, children, parent);
  43. }
  44. /// <summary>
  45. /// Initializes a new <see cref="MenuBarItem"/>.
  46. /// </summary>
  47. /// <param name="children">The items in the current menu.</param>
  48. public MenuBarItem (MenuItem [] children) : this ("", children) { }
  49. /// <summary>
  50. /// Initializes a new <see cref="MenuBarItem"/>.
  51. /// </summary>
  52. public MenuBarItem () : this (children: new MenuItem [] { }) { }
  53. void Initialize (string title, object children, MenuItem parent = null, bool isTopLevel = false)
  54. {
  55. if (!isTopLevel && children == null) {
  56. throw new ArgumentNullException (nameof (children), "The parameter cannot be null. Use an empty array instead.");
  57. }
  58. SetTitle (title ?? "");
  59. if (parent != null) {
  60. Parent = parent;
  61. }
  62. if (children is List<MenuItem []> childrenList) {
  63. var newChildren = new MenuItem [] { };
  64. foreach (var grandChild in childrenList) {
  65. foreach (var child in grandChild) {
  66. SetParent (grandChild);
  67. Array.Resize (ref newChildren, newChildren.Length + 1);
  68. newChildren [newChildren.Length - 1] = child;
  69. }
  70. }
  71. Children = newChildren;
  72. } else if (children is MenuItem [] items) {
  73. SetParent (items);
  74. Children = items;
  75. } else {
  76. Children = null;
  77. }
  78. }
  79. void SetParent (MenuItem [] children)
  80. {
  81. foreach (var child in children) {
  82. if (child is { Parent: null }) {
  83. child.Parent = this;
  84. }
  85. }
  86. }
  87. /// <summary>
  88. /// Check if a <see cref="MenuItem"/> is a <see cref="MenuBarItem"/>.
  89. /// </summary>
  90. /// <param name="menuItem"></param>
  91. /// <returns>Returns a <see cref="MenuBarItem"/> or null otherwise.</returns>
  92. public MenuBarItem SubMenu (MenuItem menuItem)
  93. {
  94. return menuItem as MenuBarItem;
  95. }
  96. /// <summary>
  97. /// Check if a <see cref="MenuItem"/> is a submenu of this MenuBar.
  98. /// </summary>
  99. /// <param name="menuItem"></param>
  100. /// <returns>Returns <c>true</c> if it is a submenu. <c>false</c> otherwise.</returns>
  101. public bool IsSubMenuOf (MenuItem menuItem)
  102. {
  103. foreach (var child in Children) {
  104. if (child == menuItem && child.Parent == menuItem.Parent) {
  105. return true;
  106. }
  107. }
  108. return false;
  109. }
  110. /// <summary>
  111. /// Get the index of a child <see cref="MenuItem"/>.
  112. /// </summary>
  113. /// <param name="children"></param>
  114. /// <returns>Returns a greater than -1 if the <see cref="MenuItem"/> is a child.</returns>
  115. public int GetChildrenIndex (MenuItem children)
  116. {
  117. int i = 0;
  118. if (Children != null) {
  119. foreach (var child in Children) {
  120. if (child == children) {
  121. return i;
  122. }
  123. i++;
  124. }
  125. }
  126. return -1;
  127. }
  128. void SetTitle (string title)
  129. {
  130. title ??= string.Empty;
  131. Title = title;
  132. }
  133. /// <summary>
  134. /// Gets or sets an array of <see cref="MenuItem"/> objects that are the children of this <see cref="MenuBarItem"/>
  135. /// </summary>
  136. /// <value>The children.</value>
  137. public MenuItem [] Children { get; set; }
  138. internal bool IsTopLevel => Parent == null && (Children == null || Children.Length == 0) && Action != null;
  139. internal void AddKeyBindings (MenuBar menuBar)
  140. {
  141. if (Children == null) {
  142. return;
  143. }
  144. foreach (var menuItem in Children.Where (m => m != null)) {
  145. if (menuItem.HotKey != default) {
  146. menuBar.KeyBindings.Add ((KeyCode)menuItem.HotKey.Value, Command.ToggleExpandCollapse);
  147. menuBar.KeyBindings.Add ((KeyCode)menuItem.HotKey.Value | KeyCode.AltMask, KeyBindingScope.HotKey, Command.ToggleExpandCollapse);
  148. }
  149. if (menuItem.Shortcut != KeyCode.Unknown && menuItem.Shortcut != KeyCode.Null) {
  150. menuBar.KeyBindings.Add (menuItem.Shortcut, KeyBindingScope.HotKey, Command.Select);
  151. }
  152. SubMenu (menuItem)?.AddKeyBindings (menuBar);
  153. }
  154. }
  155. }
  156. /// <summary>
  157. /// <para>
  158. /// Provides a menu bar that spans the top of a <see cref="Toplevel"/> View with drop-down and cascading menus.
  159. /// </para>
  160. /// <para>
  161. /// By default, any sub-sub-menus (sub-menus of the <see cref="MenuItem"/>s added to <see cref="MenuBarItem"/>s)
  162. /// are displayed in a cascading manner, where each sub-sub-menu pops out of the sub-menu frame
  163. /// (either to the right or left, depending on where the sub-menu is relative to the edge of the screen). By setting
  164. /// <see cref="UseSubMenusSingleFrame"/> to <see langword="true"/>, this behavior can be changed such that all sub-sub-menus are
  165. /// drawn within a single frame below the MenuBar.
  166. /// </para>
  167. /// </summary>
  168. /// <remarks>
  169. /// <para>
  170. /// The <see cref="MenuBar"/> appears on the first row of the <see cref="Toplevel"/> SuperView and uses the full width.
  171. /// </para>
  172. /// <para>
  173. /// See also: <see cref="ContextMenu"/>
  174. /// </para>
  175. /// <para>
  176. /// The <see cref="MenuBar"/> provides global hot keys for the application. See <see cref="MenuItem.HotKey"/>.
  177. /// </para>
  178. /// <para>
  179. /// When the menu is created key bindings for each menu item and its sub-menu items are added for each menu item's
  180. /// hot key (both alone AND with AltMask) and shortcut, if defined.
  181. /// </para>
  182. /// <para>
  183. /// If a key press matches any of the menu item's hot keys or shortcuts, the menu item's action is invoked or
  184. /// sub-menu opened.
  185. /// </para>
  186. /// <para>
  187. /// * If the menu bar is not open
  188. /// * Any shortcut defined within the menu will be invoked
  189. /// * Only hot keys defined for the menu bar items will be invoked, and only if Alt is pressed too.
  190. /// * If the menu bar is open
  191. /// * Un-shifted hot keys defined for the menu bar items will be invoked, only if the menu they belong to is open (the menu bar item's text is visible).
  192. /// * Alt-shifted hot keys defined for the menu bar items will be invoked, only if the menu they belong to is open (the menu bar item's text is visible).
  193. /// * If there is a visible hot key that duplicates a shortcut (e.g. _File and Alt-F), the hot key wins.
  194. /// </para>
  195. /// </remarks>
  196. public class MenuBar : View {
  197. internal int _selected;
  198. internal int _selectedSub;
  199. /// <summary>
  200. /// Gets or sets the array of <see cref="MenuBarItem"/>s for the menu. Only set this after the <see cref="MenuBar"/> is visible.
  201. /// </summary>
  202. /// <value>The menu array.</value>
  203. public MenuBarItem [] Menus { get; set; }
  204. /// <summary>
  205. /// The default <see cref="LineStyle"/> for <see cref="Menus"/>'s border. The default is <see cref="LineStyle.Single"/>.
  206. /// </summary>
  207. public LineStyle MenusBorderStyle { get; set; } = LineStyle.Single;
  208. bool _useSubMenusSingleFrame;
  209. /// <summary>
  210. /// Gets or sets if the sub-menus must be displayed in a single or multiple frames.
  211. /// <para>
  212. /// By default any sub-sub-menus (sub-menus of the main <see cref="MenuItem"/>s) are displayed in a cascading manner,
  213. /// where each sub-sub-menu pops out of the sub-menu frame
  214. /// (either to the right or left, depending on where the sub-menu is relative to the edge of the screen). By setting
  215. /// <see cref="UseSubMenusSingleFrame"/> to <see langword="true"/>, this behavior can be changed such that all sub-sub-menus are
  216. /// drawn within a single frame below the MenuBar.
  217. /// </para>
  218. /// </summary>
  219. public bool UseSubMenusSingleFrame {
  220. get => _useSubMenusSingleFrame;
  221. set {
  222. _useSubMenusSingleFrame = value;
  223. if (value && UseKeysUpDownAsKeysLeftRight) {
  224. _useKeysUpDownAsKeysLeftRight = false;
  225. SetNeedsDisplay ();
  226. }
  227. }
  228. }
  229. ///<inheritdoc/>
  230. public override bool Visible {
  231. get => base.Visible;
  232. set {
  233. base.Visible = value;
  234. if (!value) {
  235. CloseAllMenus ();
  236. }
  237. }
  238. }
  239. /// <summary>
  240. /// Initializes a new instance of the <see cref="MenuBar"/>.
  241. /// </summary>
  242. public MenuBar () : this (new MenuBarItem [] { }) { }
  243. /// <summary>
  244. /// Initializes a new instance of the <see cref="MenuBar"/> class with the specified set of Toplevel menu items.
  245. /// </summary>
  246. /// <param name="menus">Individual menu items; a null item will result in a separator being drawn.</param>
  247. public MenuBar (MenuBarItem [] menus) : base ()
  248. {
  249. X = 0;
  250. Y = 0;
  251. Width = Dim.Fill ();
  252. Height = 1;
  253. Menus = menus;
  254. //CanFocus = true;
  255. _selected = -1;
  256. _selectedSub = -1;
  257. ColorScheme = Colors.Menu;
  258. WantMousePositionReports = true;
  259. IsMenuOpen = false;
  260. Added += MenuBar_Added;
  261. // Things this view knows how to do
  262. AddCommand (Command.Left, () => {
  263. MoveLeft ();
  264. return true;
  265. });
  266. AddCommand (Command.Right, () => {
  267. MoveRight ();
  268. return true;
  269. });
  270. AddCommand (Command.Cancel, () => {
  271. CloseMenuBar ();
  272. return true;
  273. });
  274. AddCommand (Command.Accept, () => {
  275. ProcessMenu (_selected, Menus [_selected]);
  276. return true;
  277. });
  278. AddCommand (Command.ToggleExpandCollapse, () => SelectOrRun ());
  279. AddCommand (Command.Select, () => Run (_menuItemToSelect?.Action));
  280. // Default key bindings for this view
  281. KeyBindings.Add (KeyCode.CursorLeft, Command.Left);
  282. KeyBindings.Add (KeyCode.CursorRight, Command.Right);
  283. KeyBindings.Add (KeyCode.Esc, Command.Cancel);
  284. KeyBindings.Add (KeyCode.CursorDown, Command.Accept);
  285. KeyBindings.Add (KeyCode.Enter, Command.Accept);
  286. KeyBindings.Add ((KeyCode)Key, KeyBindingScope.HotKey, Command.ToggleExpandCollapse);
  287. KeyBindings.Add (KeyCode.CtrlMask | KeyCode.Space, KeyBindingScope.HotKey, Command.ToggleExpandCollapse);
  288. // TODO: Bindings (esp for hotkey) should be added across and then down. This currently does down then across.
  289. // TODO: As a result, _File._Save will have precedence over in "_File _Edit _ScrollbarView"
  290. // TODO: Also: Hotkeys should not work for sub-menus if they are not visible!
  291. if (Menus != null) {
  292. foreach (var menuBarItem in Menus?.Where (m => m != null)) {
  293. if (menuBarItem.HotKey != default) {
  294. KeyBindings.Add ((KeyCode)menuBarItem.HotKey.Value, Command.ToggleExpandCollapse);
  295. KeyBindings.Add ((KeyCode)menuBarItem.HotKey.Value | KeyCode.AltMask, KeyBindingScope.HotKey, Command.ToggleExpandCollapse);
  296. }
  297. if (menuBarItem.Shortcut != KeyCode.Unknown && menuBarItem.Shortcut != KeyCode.Null) {
  298. // Technically this will will never run because MenuBarItems don't have shortcuts
  299. KeyBindings.Add (menuBarItem.Shortcut, KeyBindingScope.HotKey, Command.Select);
  300. }
  301. menuBarItem.AddKeyBindings (this);
  302. }
  303. }
  304. #if SUPPORT_ALT_TO_ACTIVATE_MENU
  305. // Enable the Alt key as a menu activator
  306. Initialized += (s, e) => {
  307. if (SuperView != null) {
  308. SuperView.KeyUp += SuperView_KeyUp;
  309. }
  310. };
  311. #endif
  312. }
  313. #if SUPPORT_ALT_TO_ACTIVATE_MENU
  314. void SuperView_KeyUp (object sender, KeyEventArgs e)
  315. {
  316. if (SuperView == null || SuperView.CanFocus == false || SuperView.Visible == false) {
  317. return;
  318. }
  319. AltKeyUpHandler(e);
  320. }
  321. #endif
  322. internal void AltKeyUpHandler (Key e)
  323. {
  324. if (e.KeyCode == KeyCode.AltMask) {
  325. e.Handled = true;
  326. // User pressed Alt
  327. if (!IsMenuOpen && _openMenu == null && !_openedByAltKey) {
  328. // There's no open menu, the first menu item should be highlighted.
  329. // The right way to do this is to SetFocus(MenuBar), but for some reason
  330. // that faults.
  331. GetMouseGrabViewInstance (this)?.CleanUp ();
  332. IsMenuOpen = true;
  333. _openedByAltKey = true;
  334. _selected = 0;
  335. CanFocus = true;
  336. _lastFocused = SuperView == null ? Application.Current.MostFocused : SuperView.MostFocused;
  337. SetFocus ();
  338. SetNeedsDisplay ();
  339. Application.GrabMouse (this);
  340. } else if (!_openedByHotKey) {
  341. // There's an open menu. Close it.
  342. CleanUp ();
  343. } else {
  344. _openedByAltKey = false;
  345. _openedByHotKey = false;
  346. }
  347. }
  348. }
  349. #region Keyboard handling
  350. Key _key = Key.F9;
  351. /// <summary>
  352. /// The <see cref="Key"/> used to activate or close the menu bar by keyboard. The default is <see cref="Key.F9"/>.
  353. /// </summary>
  354. /// <remarks>
  355. /// <para>
  356. /// If the user presses any <see cref="MenuItem.HotKey"/>s defined in the <see cref="MenuBarItem"/>s, the menu bar will be activated and the sub-menu will be opened.
  357. /// </para>
  358. /// <para>
  359. /// <see cref="Key.Esc"/> will close the menu bar and any open sub-menus.
  360. /// </para>
  361. /// </remarks>
  362. public Key Key {
  363. get => _key;
  364. set {
  365. if (_key == value) {
  366. return;
  367. }
  368. KeyBindings.Remove (_key);
  369. KeyBindings.Add (value, KeyBindingScope.HotKey, Command.ToggleExpandCollapse);
  370. _key = value;
  371. }
  372. }
  373. bool _useKeysUpDownAsKeysLeftRight = false;
  374. /// <summary>
  375. /// Used for change the navigation key style.
  376. /// </summary>
  377. public bool UseKeysUpDownAsKeysLeftRight {
  378. get => _useKeysUpDownAsKeysLeftRight;
  379. set {
  380. _useKeysUpDownAsKeysLeftRight = value;
  381. if (value && UseSubMenusSingleFrame) {
  382. UseSubMenusSingleFrame = false;
  383. SetNeedsDisplay ();
  384. }
  385. }
  386. }
  387. static Rune _shortcutDelimiter = new Rune ('+');
  388. /// <summary>
  389. /// Sets or gets the shortcut delimiter separator. The default is "+".
  390. /// </summary>
  391. public static Rune ShortcutDelimiter {
  392. get => _shortcutDelimiter;
  393. set {
  394. if (_shortcutDelimiter != value) {
  395. _shortcutDelimiter = value == default ? new Rune ('+') : value;
  396. }
  397. }
  398. }
  399. /// <summary>
  400. /// The specifier character for the hot keys.
  401. /// </summary>
  402. public new static Rune HotKeySpecifier => (Rune)'_';
  403. // Set in OnInvokingKeyBindings. -1 means no menu item is selected for activation.
  404. int _menuBarItemToActivate;
  405. // Set in OnInvokingKeyBindings. null means no sub-menu is selected for activation.
  406. MenuItem _menuItemToSelect;
  407. bool _openedByAltKey;
  408. bool _openedByHotKey;
  409. /// <summary>
  410. /// Called when a key bound to Command.Select is pressed. Either activates the menu item or runs it, depending on whether it has a sub-menu.
  411. /// If the menu is open, it will close the menu bar.
  412. /// </summary>
  413. /// <returns></returns>
  414. bool SelectOrRun ()
  415. {
  416. if (!IsInitialized || !Visible) {
  417. return true;
  418. }
  419. _openedByHotKey = true;
  420. if (_menuBarItemToActivate != -1) {
  421. Activate (_menuBarItemToActivate);
  422. } else if (_menuItemToSelect != null) {
  423. Run (_menuItemToSelect.Action);
  424. } else {
  425. if (IsMenuOpen && _openMenu != null) {
  426. CloseAllMenus ();
  427. } else {
  428. OpenMenu ();
  429. }
  430. }
  431. return true;
  432. }
  433. /// <inheritdoc/>
  434. public override bool? OnInvokingKeyBindings (Key keyEvent)
  435. {
  436. // This is a bit of a hack. We want to handle the key bindings for menu bar but
  437. // InvokeKeyBindings doesn't pass any context so we can't tell which item it is for.
  438. // So before we call the base class we set SelectedItem appropriately.
  439. // TODO: Figure out if there's a way to have KeyBindings pass context instead. Maybe a KeyBindingContext property?
  440. var key = keyEvent.KeyCode;
  441. if (KeyBindings.TryGet (key, out _)) {
  442. _menuBarItemToActivate = -1;
  443. _menuItemToSelect = null;
  444. // Search for shortcuts first. If there's a shortcut, we don't want to activate the menu item.
  445. for (int i = 0; i < Menus.Length; i++) {
  446. // Recurse through the menu to find one with the shortcut.
  447. if (FindShortcutInChildMenu (key, Menus [i], out _menuItemToSelect)) {
  448. _menuBarItemToActivate = i;
  449. keyEvent.Scope = KeyBindingScope.HotKey;
  450. return base.OnInvokingKeyBindings (keyEvent);
  451. }
  452. // Now see if any of the menu bar items have a hot key that matches
  453. // Technically this is not possible because menu bar items don't have
  454. // shortcuts or Actions. But it's here for completeness.
  455. var shortcut = Menus [i]?.Shortcut;
  456. if (key == shortcut) {
  457. throw new InvalidOperationException ("Menu bar items cannot have shortcuts");
  458. }
  459. }
  460. // Search for hot keys next.
  461. for (int i = 0; i < Menus.Length; i++) {
  462. if (IsMenuOpen) {
  463. // We don't need to do anything because `Menu` will handle the key binding.
  464. //break;
  465. }
  466. // No submenu item matched (or the menu is closed)
  467. // Check if one of the menu bar item has a hot key that matches
  468. int hotKeyValue = Menus [i]?.HotKey.Value ?? default;
  469. var hotKey = (KeyCode)hotKeyValue;
  470. if (hotKey != KeyCode.Null) {
  471. bool matches = key == hotKey || key == (hotKey | KeyCode.AltMask);
  472. if (IsMenuOpen) {
  473. // If the menu is open, only match if Alt is not pressed.
  474. matches = key == hotKey;
  475. }
  476. if (matches) {
  477. _menuBarItemToActivate = i;
  478. keyEvent.Scope = KeyBindingScope.HotKey;
  479. break;
  480. }
  481. }
  482. }
  483. }
  484. return base.OnInvokingKeyBindings (keyEvent);
  485. }
  486. // TODO: Update to use Key instead of KeyCode
  487. // Recurse the child menus looking for a shortcut that matches the key
  488. bool FindShortcutInChildMenu (KeyCode key, MenuBarItem menuBarItem, out MenuItem menuItemToSelect)
  489. {
  490. menuItemToSelect = null;
  491. if (key == KeyCode.Null || menuBarItem?.Children == null) {
  492. return false;
  493. }
  494. for (int c = 0; c < menuBarItem.Children.Length; c++) {
  495. var menuItem = menuBarItem.Children [c];
  496. if (key == menuItem?.Shortcut) {
  497. menuItemToSelect = menuItem;
  498. return true;
  499. }
  500. var subMenu = menuBarItem.SubMenu (menuItem);
  501. if (subMenu != null) {
  502. if (FindShortcutInChildMenu (key, subMenu, out menuItemToSelect)) {
  503. return true;
  504. }
  505. }
  506. }
  507. return false;
  508. }
  509. #endregion Keyboard handling
  510. bool _initialCanFocus;
  511. void MenuBar_Added (object sender, SuperViewChangedEventArgs e)
  512. {
  513. _initialCanFocus = CanFocus;
  514. Added -= MenuBar_Added;
  515. }
  516. bool _isCleaning;
  517. internal void CleanUp ()
  518. {
  519. _isCleaning = true;
  520. if (_openMenu != null) {
  521. CloseAllMenus ();
  522. }
  523. _openedByAltKey = false;
  524. _openedByHotKey = false;
  525. IsMenuOpen = false;
  526. _selected = -1;
  527. CanFocus = _initialCanFocus;
  528. if (_lastFocused != null) {
  529. _lastFocused.SetFocus ();
  530. }
  531. SetNeedsDisplay ();
  532. Application.UngrabMouse ();
  533. _isCleaning = false;
  534. }
  535. // The column where the MenuBar starts
  536. static int _xOrigin = 0;
  537. // Spaces before the Title
  538. static int _leftPadding = 1;
  539. // Spaces after the Title
  540. static int _rightPadding = 1;
  541. // Spaces after the submenu Title, before Help
  542. static int _parensAroundHelp = 3;
  543. ///<inheritdoc/>
  544. public override void OnDrawContent (Rect contentArea)
  545. {
  546. Move (0, 0);
  547. Driver.SetAttribute (GetNormalColor ());
  548. for (int i = 0; i < Frame.Width; i++) {
  549. Driver.AddRune ((Rune)' ');
  550. }
  551. Move (1, 0);
  552. int pos = 0;
  553. for (int i = 0; i < Menus.Length; i++) {
  554. var menu = Menus [i];
  555. Move (pos, 0);
  556. Attribute hotColor, normalColor;
  557. if (i == _selected && IsMenuOpen) {
  558. hotColor = i == _selected ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  559. normalColor = i == _selected ? ColorScheme.Focus : GetNormalColor ();
  560. } else {
  561. hotColor = ColorScheme.HotNormal;
  562. normalColor = GetNormalColor ();
  563. }
  564. // Note Help on MenuBar is drawn with parens around it
  565. DrawHotString (string.IsNullOrEmpty (menu.Help) ? $" {menu.Title} " : $" {menu.Title} ({menu.Help}) ", hotColor, normalColor);
  566. pos += _leftPadding + menu.TitleLength + (menu.Help.GetColumns () > 0 ? _leftPadding + menu.Help.GetColumns () + _parensAroundHelp : 0) + _rightPadding;
  567. }
  568. PositionCursor ();
  569. }
  570. ///<inheritdoc/>
  571. public override void PositionCursor ()
  572. {
  573. if (_selected == -1 && HasFocus && Menus.Length > 0) {
  574. _selected = 0;
  575. }
  576. int pos = 0;
  577. for (int i = 0; i < Menus.Length; i++) {
  578. if (i == _selected) {
  579. pos++;
  580. Move (pos + 1, 0);
  581. return;
  582. } else {
  583. pos += _leftPadding + Menus [i].TitleLength + (Menus [i].Help.GetColumns () > 0 ? Menus [i].Help.GetColumns () + _parensAroundHelp : 0) + _rightPadding;
  584. }
  585. }
  586. }
  587. /// <summary>
  588. /// Called when an item is selected; Runs the action.
  589. /// </summary>
  590. /// <param name="item"></param>
  591. internal bool SelectItem (MenuItem item)
  592. {
  593. if (item?.Action == null) {
  594. return false;
  595. }
  596. Application.UngrabMouse ();
  597. CloseAllMenus ();
  598. Application.Refresh ();
  599. _openedByAltKey = true;
  600. return Run (item?.Action);
  601. }
  602. internal bool Run (Action action)
  603. {
  604. if (action == null) {
  605. return false;
  606. }
  607. Application.MainLoop.AddIdle (() => {
  608. action ();
  609. return false;
  610. });
  611. return true;
  612. }
  613. /// <summary>
  614. /// Raised as a menu is opening.
  615. /// </summary>
  616. public event EventHandler<MenuOpeningEventArgs> MenuOpening;
  617. /// <summary>
  618. /// Raised when a menu is opened.
  619. /// </summary>
  620. public event EventHandler<MenuOpenedEventArgs> MenuOpened;
  621. /// <summary>
  622. /// Raised when a menu is closing passing <see cref="MenuClosingEventArgs"/>.
  623. /// </summary>
  624. public event EventHandler<MenuClosingEventArgs> MenuClosing;
  625. /// <summary>
  626. /// Raised when all the menu is closed.
  627. /// </summary>
  628. public event EventHandler MenuAllClosed;
  629. // BUGBUG: Hack
  630. internal Menu _openMenu;
  631. Menu _ocm;
  632. internal Menu openCurrentMenu {
  633. get => _ocm;
  634. set {
  635. if (_ocm != value) {
  636. _ocm = value;
  637. if (_ocm != null && _ocm._currentChild > -1) {
  638. OnMenuOpened ();
  639. }
  640. }
  641. }
  642. }
  643. internal List<Menu> _openSubMenu;
  644. View _previousFocused;
  645. internal bool _isMenuOpening;
  646. internal bool _isMenuClosing;
  647. /// <summary>
  648. /// <see langword="true"/> if the menu is open; otherwise <see langword="true"/>.
  649. /// </summary>
  650. public bool IsMenuOpen { get; protected set; }
  651. /// <summary>
  652. /// Virtual method that will invoke the <see cref="MenuOpening"/> event if it's defined.
  653. /// </summary>
  654. /// <param name="currentMenu">The current menu to be replaced.</param>
  655. /// <returns>Returns the <see cref="MenuOpeningEventArgs"/></returns>
  656. public virtual MenuOpeningEventArgs OnMenuOpening (MenuBarItem currentMenu)
  657. {
  658. var ev = new MenuOpeningEventArgs (currentMenu);
  659. MenuOpening?.Invoke (this, ev);
  660. return ev;
  661. }
  662. /// <summary>
  663. /// Virtual method that will invoke the <see cref="MenuOpened"/> event if it's defined.
  664. /// </summary>
  665. public virtual void OnMenuOpened ()
  666. {
  667. MenuItem mi = null;
  668. MenuBarItem parent;
  669. if (openCurrentMenu._barItems.Children != null && openCurrentMenu._barItems.Children.Length > 0
  670. && openCurrentMenu?._currentChild > -1) {
  671. parent = openCurrentMenu._barItems;
  672. mi = parent.Children [openCurrentMenu._currentChild];
  673. } else if (openCurrentMenu._barItems.IsTopLevel) {
  674. parent = null;
  675. mi = openCurrentMenu._barItems;
  676. } else {
  677. parent = _openMenu._barItems;
  678. mi = parent.Children [_openMenu._currentChild];
  679. }
  680. MenuOpened?.Invoke (this, new MenuOpenedEventArgs (parent, mi));
  681. }
  682. /// <summary>
  683. /// Virtual method that will invoke the <see cref="MenuClosing"/>.
  684. /// </summary>
  685. /// <param name="currentMenu">The current menu to be closed.</param>
  686. /// <param name="reopen">Whether the current menu will be reopen.</param>
  687. /// <param name="isSubMenu">Whether is a sub-menu or not.</param>
  688. public virtual MenuClosingEventArgs OnMenuClosing (MenuBarItem currentMenu, bool reopen, bool isSubMenu)
  689. {
  690. var ev = new MenuClosingEventArgs (currentMenu, reopen, isSubMenu);
  691. MenuClosing?.Invoke (this, ev);
  692. return ev;
  693. }
  694. /// <summary>
  695. /// Virtual method that will invoke the <see cref="MenuAllClosed"/>.
  696. /// </summary>
  697. public virtual void OnMenuAllClosed ()
  698. {
  699. MenuAllClosed?.Invoke (this, EventArgs.Empty);
  700. }
  701. View _lastFocused;
  702. /// <summary>
  703. /// Gets the view that was last focused before opening the menu.
  704. /// </summary>
  705. public View LastFocused { get; private set; }
  706. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem subMenu = null)
  707. {
  708. _isMenuOpening = true;
  709. var newMenu = OnMenuOpening (Menus [index]);
  710. if (newMenu.Cancel) {
  711. _isMenuOpening = false;
  712. return;
  713. }
  714. if (newMenu.NewMenuBarItem != null) {
  715. Menus [index] = newMenu.NewMenuBarItem;
  716. }
  717. int pos = 0;
  718. switch (subMenu) {
  719. case null:
  720. // Open a submenu below a MenuBar
  721. _lastFocused ??= SuperView == null ? Application.Current?.MostFocused : SuperView.MostFocused;
  722. if (_openSubMenu != null && !CloseMenu (false, true)) {
  723. return;
  724. }
  725. if (_openMenu != null) {
  726. Application.Current.Remove (_openMenu);
  727. _openMenu.Dispose ();
  728. _openMenu = null;
  729. }
  730. // This positions the submenu horizontally aligned with the first character of the
  731. // text belonging to the menu
  732. for (int i = 0; i < index; i++) {
  733. pos += Menus [i].TitleLength + (Menus [i].Help.GetColumns () > 0 ? Menus [i].Help.GetColumns () + 2 : 0) + _leftPadding + _rightPadding;
  734. }
  735. var locationOffset = Point.Empty;
  736. // if SuperView is null then it's from a ContextMenu
  737. if (SuperView == null) {
  738. locationOffset = GetScreenOffset ();
  739. }
  740. if (SuperView != null && SuperView != Application.Current) {
  741. locationOffset.X += SuperView.Border.Thickness.Left;
  742. locationOffset.Y += SuperView.Border.Thickness.Top;
  743. }
  744. _openMenu = new Menu (this, Frame.X + pos + locationOffset.X, Frame.Y + 1 + locationOffset.Y, Menus [index], null, MenusBorderStyle);
  745. openCurrentMenu = _openMenu;
  746. openCurrentMenu._previousSubFocused = _openMenu;
  747. Application.Current.Add (_openMenu);
  748. _openMenu.SetFocus ();
  749. break;
  750. default:
  751. // Opens a submenu next to another submenu (openSubMenu)
  752. if (_openSubMenu == null) {
  753. _openSubMenu = new List<Menu> ();
  754. }
  755. if (sIndex > -1) {
  756. RemoveSubMenu (sIndex);
  757. } else {
  758. var last = _openSubMenu.Count > 0 ? _openSubMenu.Last () : _openMenu;
  759. if (!UseSubMenusSingleFrame) {
  760. locationOffset = GetLocationOffset ();
  761. openCurrentMenu = new Menu (this, last.Frame.Left + last.Frame.Width + locationOffset.X, last.Frame.Top + locationOffset.Y + last._currentChild, subMenu, last, MenusBorderStyle);
  762. } else {
  763. var first = _openSubMenu.Count > 0 ? _openSubMenu.First () : _openMenu;
  764. // 2 is for the parent and the separator
  765. var mbi = new MenuItem [2 + subMenu.Children.Length];
  766. mbi [0] = new MenuItem () { Title = subMenu.Title, Parent = subMenu };
  767. mbi [1] = null;
  768. for (int j = 0; j < subMenu.Children.Length; j++) {
  769. mbi [j + 2] = subMenu.Children [j];
  770. }
  771. var newSubMenu = new MenuBarItem (mbi) { Parent = subMenu };
  772. openCurrentMenu = new Menu (this, first.Frame.Left, first.Frame.Top, newSubMenu, null, MenusBorderStyle);
  773. last.Visible = false;
  774. Application.GrabMouse (openCurrentMenu);
  775. }
  776. openCurrentMenu._previousSubFocused = last._previousSubFocused;
  777. _openSubMenu.Add (openCurrentMenu);
  778. Application.Current.Add (openCurrentMenu);
  779. }
  780. _selectedSub = _openSubMenu.Count - 1;
  781. if (_selectedSub > -1 && SelectEnabledItem (openCurrentMenu._barItems.Children, openCurrentMenu._currentChild, out openCurrentMenu._currentChild)) {
  782. openCurrentMenu.SetFocus ();
  783. }
  784. break;
  785. }
  786. _isMenuOpening = false;
  787. IsMenuOpen = true;
  788. }
  789. Point GetLocationOffset ()
  790. {
  791. if (MenusBorderStyle != LineStyle.None) {
  792. return new Point (0, 1);
  793. }
  794. return new Point (-2, 0);
  795. }
  796. /// <summary>
  797. /// Opens the Menu programatically, as though the F9 key were pressed.
  798. /// </summary>
  799. public void OpenMenu ()
  800. {
  801. var mbar = GetMouseGrabViewInstance (this);
  802. if (mbar != null) {
  803. mbar.CleanUp ();
  804. }
  805. if (_openMenu != null) {
  806. return;
  807. }
  808. _selected = 0;
  809. SetNeedsDisplay ();
  810. _previousFocused = SuperView == null ? Application.Current.Focused : SuperView.Focused;
  811. OpenMenu (_selected);
  812. if (!SelectEnabledItem (openCurrentMenu._barItems.Children, openCurrentMenu._currentChild, out openCurrentMenu._currentChild) && !CloseMenu (false)) {
  813. return;
  814. }
  815. if (!openCurrentMenu.CheckSubMenu ()) {
  816. return;
  817. }
  818. Application.GrabMouse (this);
  819. }
  820. // Activates the menu, handles either first focus, or activating an entry when it was already active
  821. // For mouse events.
  822. internal void Activate (int idx, int sIdx = -1, MenuBarItem subMenu = null)
  823. {
  824. _selected = idx;
  825. _selectedSub = sIdx;
  826. if (_openMenu == null) {
  827. _previousFocused = SuperView == null ? Application.Current?.Focused ?? null : SuperView.Focused;
  828. }
  829. OpenMenu (idx, sIdx, subMenu);
  830. SetNeedsDisplay ();
  831. }
  832. internal bool SelectEnabledItem (IEnumerable<MenuItem> chldren, int current, out int newCurrent, bool forward = true)
  833. {
  834. if (chldren == null) {
  835. newCurrent = -1;
  836. return true;
  837. }
  838. IEnumerable<MenuItem> childrens;
  839. if (forward) {
  840. childrens = chldren;
  841. } else {
  842. childrens = chldren.Reverse ();
  843. }
  844. int count;
  845. if (forward) {
  846. count = -1;
  847. } else {
  848. count = childrens.Count ();
  849. }
  850. foreach (var child in childrens) {
  851. if (forward) {
  852. if (++count < current) {
  853. continue;
  854. }
  855. } else {
  856. if (--count > current) {
  857. continue;
  858. }
  859. }
  860. if (child == null || !child.IsEnabled ()) {
  861. if (forward) {
  862. current++;
  863. } else {
  864. current--;
  865. }
  866. } else {
  867. newCurrent = current;
  868. return true;
  869. }
  870. }
  871. newCurrent = -1;
  872. return false;
  873. }
  874. /// <summary>
  875. /// Closes the Menu programmatically if open and not canceled (as though F9 were pressed).
  876. /// </summary>
  877. public bool CloseMenu (bool ignoreUseSubMenusSingleFrame = false)
  878. {
  879. return CloseMenu (false, false, ignoreUseSubMenusSingleFrame);
  880. }
  881. bool _reopen;
  882. internal bool CloseMenu (bool reopen = false, bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  883. {
  884. var mbi = isSubMenu ? openCurrentMenu._barItems : _openMenu?._barItems;
  885. if (UseSubMenusSingleFrame && mbi != null &&
  886. !ignoreUseSubMenusSingleFrame && mbi.Parent != null) {
  887. return false;
  888. }
  889. _isMenuClosing = true;
  890. _reopen = reopen;
  891. var args = OnMenuClosing (mbi, reopen, isSubMenu);
  892. if (args.Cancel) {
  893. _isMenuClosing = false;
  894. if (args.CurrentMenu.Parent != null) {
  895. _openMenu._currentChild = ((MenuBarItem)args.CurrentMenu.Parent).Children.IndexOf (args.CurrentMenu);
  896. }
  897. return false;
  898. }
  899. switch (isSubMenu) {
  900. case false:
  901. if (_openMenu != null) {
  902. Application.Current.Remove (_openMenu);
  903. }
  904. SetNeedsDisplay ();
  905. if (_previousFocused != null && _previousFocused is Menu && _openMenu != null && _previousFocused.ToString () != openCurrentMenu.ToString ()) {
  906. _previousFocused.SetFocus ();
  907. }
  908. _openMenu?.Dispose ();
  909. _openMenu = null;
  910. if (_lastFocused is Menu || _lastFocused is MenuBar) {
  911. _lastFocused = null;
  912. }
  913. LastFocused = _lastFocused;
  914. _lastFocused = null;
  915. if (LastFocused != null && LastFocused.CanFocus) {
  916. if (!reopen) {
  917. _selected = -1;
  918. }
  919. if (_openSubMenu != null) {
  920. _openSubMenu = null;
  921. }
  922. if (openCurrentMenu != null) {
  923. Application.Current.Remove (openCurrentMenu);
  924. openCurrentMenu.Dispose ();
  925. openCurrentMenu = null;
  926. }
  927. LastFocused.SetFocus ();
  928. } else if (_openSubMenu == null || _openSubMenu.Count == 0) {
  929. CloseAllMenus ();
  930. } else {
  931. SetFocus ();
  932. PositionCursor ();
  933. }
  934. IsMenuOpen = false;
  935. break;
  936. case true:
  937. _selectedSub = -1;
  938. SetNeedsDisplay ();
  939. RemoveAllOpensSubMenus ();
  940. openCurrentMenu._previousSubFocused.SetFocus ();
  941. _openSubMenu = null;
  942. IsMenuOpen = true;
  943. break;
  944. }
  945. _reopen = false;
  946. _isMenuClosing = false;
  947. return true;
  948. }
  949. void RemoveSubMenu (int index, bool ignoreUseSubMenusSingleFrame = false)
  950. {
  951. if (_openSubMenu == null || UseSubMenusSingleFrame
  952. && !ignoreUseSubMenusSingleFrame && _openSubMenu.Count == 0) {
  953. return;
  954. }
  955. for (int i = _openSubMenu.Count - 1; i > index; i--) {
  956. _isMenuClosing = true;
  957. Menu menu;
  958. if (_openSubMenu.Count - 1 > 0) {
  959. menu = _openSubMenu [i - 1];
  960. } else {
  961. menu = _openMenu;
  962. }
  963. if (!menu.Visible) {
  964. menu.Visible = true;
  965. }
  966. openCurrentMenu = menu;
  967. openCurrentMenu.SetFocus ();
  968. if (_openSubMenu != null) {
  969. menu = _openSubMenu [i];
  970. Application.Current.Remove (menu);
  971. _openSubMenu.Remove (menu);
  972. menu.Dispose ();
  973. }
  974. RemoveSubMenu (i, ignoreUseSubMenusSingleFrame);
  975. }
  976. if (_openSubMenu.Count > 0) {
  977. openCurrentMenu = _openSubMenu.Last ();
  978. }
  979. _isMenuClosing = false;
  980. }
  981. internal void RemoveAllOpensSubMenus ()
  982. {
  983. if (_openSubMenu != null) {
  984. foreach (var item in _openSubMenu) {
  985. Application.Current.Remove (item);
  986. item.Dispose ();
  987. }
  988. }
  989. }
  990. internal void CloseAllMenus ()
  991. {
  992. if (!_isMenuOpening && !_isMenuClosing) {
  993. if (_openSubMenu != null && !CloseMenu (false, true, true)) {
  994. return;
  995. }
  996. if (!CloseMenu (false)) {
  997. return;
  998. }
  999. if (LastFocused != null && LastFocused != this) {
  1000. _selected = -1;
  1001. }
  1002. Application.UngrabMouse ();
  1003. }
  1004. IsMenuOpen = false;
  1005. _openedByAltKey = false;
  1006. _openedByHotKey = false;
  1007. OnMenuAllClosed ();
  1008. }
  1009. internal void PreviousMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  1010. {
  1011. switch (isSubMenu) {
  1012. case false:
  1013. if (_selected <= 0) {
  1014. _selected = Menus.Length - 1;
  1015. } else {
  1016. _selected--;
  1017. }
  1018. if (_selected > -1 && !CloseMenu (true, false, ignoreUseSubMenusSingleFrame)) {
  1019. return;
  1020. }
  1021. OpenMenu (_selected);
  1022. if (!SelectEnabledItem (openCurrentMenu._barItems.Children, openCurrentMenu._currentChild, out openCurrentMenu._currentChild, false)) {
  1023. openCurrentMenu._currentChild = 0;
  1024. }
  1025. break;
  1026. case true:
  1027. if (_selectedSub > -1) {
  1028. _selectedSub--;
  1029. RemoveSubMenu (_selectedSub, ignoreUseSubMenusSingleFrame);
  1030. SetNeedsDisplay ();
  1031. } else {
  1032. PreviousMenu ();
  1033. }
  1034. break;
  1035. }
  1036. }
  1037. internal void NextMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  1038. {
  1039. switch (isSubMenu) {
  1040. case false:
  1041. if (_selected == -1) {
  1042. _selected = 0;
  1043. } else if (_selected + 1 == Menus.Length) {
  1044. _selected = 0;
  1045. } else {
  1046. _selected++;
  1047. }
  1048. if (_selected > -1 && !CloseMenu (true, ignoreUseSubMenusSingleFrame)) {
  1049. return;
  1050. }
  1051. OpenMenu (_selected);
  1052. SelectEnabledItem (openCurrentMenu._barItems.Children, openCurrentMenu._currentChild, out openCurrentMenu._currentChild);
  1053. break;
  1054. case true:
  1055. if (UseKeysUpDownAsKeysLeftRight) {
  1056. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame)) {
  1057. NextMenu (false, ignoreUseSubMenusSingleFrame);
  1058. }
  1059. } else {
  1060. var subMenu = openCurrentMenu._currentChild > -1 && openCurrentMenu._barItems.Children.Length > 0
  1061. ? openCurrentMenu._barItems.SubMenu (openCurrentMenu._barItems.Children [openCurrentMenu._currentChild])
  1062. : null;
  1063. if ((_selectedSub == -1 || _openSubMenu == null || _openSubMenu?.Count - 1 == _selectedSub) && subMenu == null) {
  1064. if (_openSubMenu != null && !CloseMenu (false, true)) {
  1065. return;
  1066. }
  1067. NextMenu (false, ignoreUseSubMenusSingleFrame);
  1068. } else if (subMenu != null || openCurrentMenu._currentChild > -1
  1069. && !openCurrentMenu._barItems.Children [openCurrentMenu._currentChild].IsFromSubMenu) {
  1070. _selectedSub++;
  1071. openCurrentMenu.CheckSubMenu ();
  1072. } else {
  1073. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame)) {
  1074. NextMenu (false, ignoreUseSubMenusSingleFrame);
  1075. }
  1076. return;
  1077. }
  1078. SetNeedsDisplay ();
  1079. if (UseKeysUpDownAsKeysLeftRight) {
  1080. openCurrentMenu.CheckSubMenu ();
  1081. }
  1082. }
  1083. break;
  1084. }
  1085. }
  1086. void ProcessMenu (int i, MenuBarItem mi)
  1087. {
  1088. if (_selected < 0 && IsMenuOpen) {
  1089. return;
  1090. }
  1091. if (mi.IsTopLevel) {
  1092. BoundsToScreen (i, 0, out int rx, out int ry);
  1093. var menu = new Menu (this, rx, ry, mi, null, MenusBorderStyle);
  1094. menu.Run (mi.Action);
  1095. menu.Dispose ();
  1096. } else {
  1097. Application.GrabMouse (this);
  1098. _selected = i;
  1099. OpenMenu (i);
  1100. if (!SelectEnabledItem (openCurrentMenu._barItems.Children, openCurrentMenu._currentChild, out openCurrentMenu._currentChild) && !CloseMenu (false)) {
  1101. return;
  1102. }
  1103. if (!openCurrentMenu.CheckSubMenu ()) {
  1104. return;
  1105. }
  1106. }
  1107. SetNeedsDisplay ();
  1108. }
  1109. void CloseMenuBar ()
  1110. {
  1111. if (!CloseMenu (false)) {
  1112. return;
  1113. }
  1114. if (_openedByAltKey) {
  1115. _openedByAltKey = false;
  1116. LastFocused?.SetFocus ();
  1117. }
  1118. SetNeedsDisplay ();
  1119. }
  1120. void MoveRight ()
  1121. {
  1122. _selected = (_selected + 1) % Menus.Length;
  1123. OpenMenu (_selected);
  1124. SetNeedsDisplay ();
  1125. }
  1126. void MoveLeft ()
  1127. {
  1128. _selected--;
  1129. if (_selected < 0) {
  1130. _selected = Menus.Length - 1;
  1131. }
  1132. OpenMenu (_selected);
  1133. SetNeedsDisplay ();
  1134. }
  1135. #region Mouse Handling
  1136. ///<inheritdoc/>
  1137. public override bool OnEnter (View view)
  1138. {
  1139. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  1140. return base.OnEnter (view);
  1141. }
  1142. ///<inheritdoc/>
  1143. public override bool OnLeave (View view)
  1144. {
  1145. if ((!(view is MenuBar) && !(view is Menu) || !(view is MenuBar) && !(view is Menu) && _openMenu != null) && !_isCleaning && !_reopen) {
  1146. CleanUp ();
  1147. }
  1148. return base.OnLeave (view);
  1149. }
  1150. ///<inheritdoc/>
  1151. public override bool MouseEvent (MouseEvent me)
  1152. {
  1153. if (!_handled && !HandleGrabView (me, this)) {
  1154. return false;
  1155. }
  1156. _handled = false;
  1157. if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked || me.Flags == MouseFlags.Button1Clicked ||
  1158. me.Flags == MouseFlags.ReportMousePosition && _selected > -1 ||
  1159. me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && _selected > -1) {
  1160. int pos = _xOrigin;
  1161. Point locationOffset = default;
  1162. if (SuperView != null) {
  1163. locationOffset.X += SuperView.Border.Thickness.Left;
  1164. locationOffset.Y += SuperView.Border.Thickness.Top;
  1165. }
  1166. int cx = me.X - locationOffset.X;
  1167. for (int i = 0; i < Menus.Length; i++) {
  1168. if (cx >= pos && cx < pos + _leftPadding + Menus [i].TitleLength + Menus [i].Help.GetColumns () + _rightPadding) {
  1169. if (me.Flags == MouseFlags.Button1Clicked) {
  1170. if (Menus [i].IsTopLevel) {
  1171. BoundsToScreen (i, 0, out int rx, out int ry);
  1172. var menu = new Menu (this, rx, ry, Menus [i], null, MenusBorderStyle);
  1173. menu.Run (Menus [i].Action);
  1174. menu.Dispose ();
  1175. } else if (!IsMenuOpen) {
  1176. Activate (i);
  1177. }
  1178. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked) {
  1179. if (IsMenuOpen && !Menus [i].IsTopLevel) {
  1180. CloseAllMenus ();
  1181. } else if (!Menus [i].IsTopLevel) {
  1182. Activate (i);
  1183. }
  1184. } else if (_selected != i && _selected > -1 && (me.Flags == MouseFlags.ReportMousePosition ||
  1185. me.Flags == MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)) {
  1186. if (IsMenuOpen) {
  1187. if (!CloseMenu (true, false)) {
  1188. return true;
  1189. }
  1190. Activate (i);
  1191. }
  1192. } else if (IsMenuOpen) {
  1193. if (!UseSubMenusSingleFrame || UseSubMenusSingleFrame && openCurrentMenu != null
  1194. && openCurrentMenu._barItems.Parent != null && openCurrentMenu._barItems.Parent.Parent != Menus [i]) {
  1195. Activate (i);
  1196. }
  1197. }
  1198. return true;
  1199. } else if (i == Menus.Length - 1 && me.Flags == MouseFlags.Button1Clicked) {
  1200. if (IsMenuOpen && !Menus [i].IsTopLevel) {
  1201. CloseAllMenus ();
  1202. return true;
  1203. }
  1204. }
  1205. pos += _leftPadding + Menus [i].TitleLength + _rightPadding;
  1206. }
  1207. }
  1208. return false;
  1209. }
  1210. internal bool _handled;
  1211. internal bool _isContextMenuLoading;
  1212. internal bool HandleGrabView (MouseEvent me, View current)
  1213. {
  1214. if (Application.MouseGrabView != null) {
  1215. if (me.View is MenuBar || me.View is Menu) {
  1216. var mbar = GetMouseGrabViewInstance (me.View);
  1217. if (mbar != null) {
  1218. if (me.Flags == MouseFlags.Button1Clicked) {
  1219. mbar.CleanUp ();
  1220. Application.GrabMouse (me.View);
  1221. } else {
  1222. _handled = false;
  1223. return false;
  1224. }
  1225. }
  1226. if (me.View != current) {
  1227. Application.UngrabMouse ();
  1228. var v = me.View;
  1229. Application.GrabMouse (v);
  1230. MouseEvent nme;
  1231. if (me.Y > -1) {
  1232. var newxy = v.ScreenToFrame (me.X, me.Y);
  1233. nme = new MouseEvent () {
  1234. X = newxy.X,
  1235. Y = newxy.Y,
  1236. Flags = me.Flags,
  1237. OfX = me.X - newxy.X,
  1238. OfY = me.Y - newxy.Y,
  1239. View = v
  1240. };
  1241. } else {
  1242. nme = new MouseEvent () {
  1243. X = me.X + current.Frame.X,
  1244. Y = 0,
  1245. Flags = me.Flags,
  1246. View = v
  1247. };
  1248. }
  1249. v.MouseEvent (nme);
  1250. return false;
  1251. }
  1252. } else if (!_isContextMenuLoading && !(me.View is MenuBar || me.View is Menu)
  1253. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  1254. Application.UngrabMouse ();
  1255. if (IsMenuOpen) {
  1256. CloseAllMenus ();
  1257. }
  1258. _handled = false;
  1259. return false;
  1260. } else {
  1261. _handled = false;
  1262. _isContextMenuLoading = false;
  1263. return false;
  1264. }
  1265. } else if (!IsMenuOpen && (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked
  1266. || me.Flags == MouseFlags.Button1TripleClicked || me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))) {
  1267. Application.GrabMouse (current);
  1268. } else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu)) {
  1269. Application.GrabMouse (me.View);
  1270. } else {
  1271. _handled = false;
  1272. return false;
  1273. }
  1274. _handled = true;
  1275. return true;
  1276. }
  1277. MenuBar GetMouseGrabViewInstance (View view)
  1278. {
  1279. if (view == null || Application.MouseGrabView == null) {
  1280. return null;
  1281. }
  1282. MenuBar hostView = null;
  1283. if (view is MenuBar) {
  1284. hostView = (MenuBar)view;
  1285. } else if (view is Menu) {
  1286. hostView = ((Menu)view)._host;
  1287. }
  1288. var grabView = Application.MouseGrabView;
  1289. MenuBar hostGrabView = null;
  1290. if (grabView is MenuBar) {
  1291. hostGrabView = (MenuBar)grabView;
  1292. } else if (grabView is Menu) {
  1293. hostGrabView = ((Menu)grabView)._host;
  1294. }
  1295. return hostView != hostGrabView ? hostGrabView : null;
  1296. }
  1297. #endregion Mouse Handling
  1298. /// <summary>
  1299. /// Gets the superview location offset relative to the <see cref="ConsoleDriver"/> location.
  1300. /// </summary>
  1301. /// <returns>The location offset.</returns>
  1302. internal Point GetScreenOffset ()
  1303. {
  1304. if (Driver == null) {
  1305. return Point.Empty;
  1306. }
  1307. var superViewFrame = SuperView == null ? new Rect (0, 0, Driver.Cols, Driver.Rows) : SuperView.Frame;
  1308. var sv = SuperView == null ? Application.Current : SuperView;
  1309. var boundsOffset = sv.GetBoundsOffset ();
  1310. return new Point (superViewFrame.X - sv.Frame.X - boundsOffset.X,
  1311. superViewFrame.Y - sv.Frame.Y - boundsOffset.Y);
  1312. }
  1313. /// <summary>
  1314. /// Gets the <see cref="Application.Current"/> location offset relative to the <see cref="ConsoleDriver"/> location.
  1315. /// </summary>
  1316. /// <returns>The location offset.</returns>
  1317. internal Point GetScreenOffsetFromCurrent ()
  1318. {
  1319. var screen = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1320. var currentFrame = Application.Current.Frame;
  1321. var boundsOffset = Application.Top.GetBoundsOffset ();
  1322. return new Point (screen.X - currentFrame.X - boundsOffset.X
  1323. , screen.Y - currentFrame.Y - boundsOffset.Y);
  1324. }
  1325. }