MenuBar.cs 59 KB

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