MenuBar.cs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940
  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 (KeyCode.CursorLeft, Command.Left);
  271. KeyBindings.Add (KeyCode.CursorRight, Command.Right);
  272. KeyBindings.Add (KeyCode.Esc, Command.Cancel);
  273. KeyBindings.Add (KeyCode.CursorDown, Command.Accept);
  274. KeyBindings.Add (KeyCode.Enter, Command.Accept);
  275. KeyBindings.Add ((KeyCode)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 (Rect contentArea)
  405. {
  406. Move (0, 0);
  407. Driver.SetAttribute (GetNormalColor ());
  408. for (var i = 0; i < Frame.Width; i++)
  409. {
  410. Driver.AddRune ((Rune)' ');
  411. }
  412. Move (1, 0);
  413. var pos = 0;
  414. for (var i = 0; i < Menus.Length; i++)
  415. {
  416. MenuBarItem menu = Menus [i];
  417. Move (pos, 0);
  418. Attribute hotColor, normalColor;
  419. if (i == _selected && IsMenuOpen)
  420. {
  421. hotColor = i == _selected ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  422. normalColor = i == _selected ? ColorScheme.Focus : GetNormalColor ();
  423. }
  424. else
  425. {
  426. hotColor = ColorScheme.HotNormal;
  427. normalColor = GetNormalColor ();
  428. }
  429. // Note Help on MenuBar is drawn with parens around it
  430. DrawHotString (
  431. string.IsNullOrEmpty (menu.Help) ? $" {menu.Title} " : $" {menu.Title} ({menu.Help}) ",
  432. hotColor,
  433. normalColor
  434. );
  435. pos += _leftPadding
  436. + menu.TitleLength
  437. + (menu.Help.GetColumns () > 0
  438. ? _leftPadding + menu.Help.GetColumns () + _parensAroundHelp
  439. : 0)
  440. + _rightPadding;
  441. }
  442. PositionCursor ();
  443. }
  444. /// <summary>Virtual method that will invoke the <see cref="MenuAllClosed"/>.</summary>
  445. public virtual void OnMenuAllClosed () { MenuAllClosed?.Invoke (this, EventArgs.Empty); }
  446. /// <summary>Virtual method that will invoke the <see cref="MenuClosing"/>.</summary>
  447. /// <param name="currentMenu">The current menu to be closed.</param>
  448. /// <param name="reopen">Whether the current menu will be reopen.</param>
  449. /// <param name="isSubMenu">Whether is a sub-menu or not.</param>
  450. public virtual MenuClosingEventArgs OnMenuClosing (MenuBarItem currentMenu, bool reopen, bool isSubMenu)
  451. {
  452. var ev = new MenuClosingEventArgs (currentMenu, reopen, isSubMenu);
  453. MenuClosing?.Invoke (this, ev);
  454. return ev;
  455. }
  456. /// <summary>Virtual method that will invoke the <see cref="MenuOpened"/> event if it's defined.</summary>
  457. public virtual void OnMenuOpened ()
  458. {
  459. MenuItem mi = null;
  460. MenuBarItem parent;
  461. if (openCurrentMenu.BarItems.Children != null
  462. && openCurrentMenu.BarItems!.Children.Length > 0
  463. && openCurrentMenu?._currentChild > -1)
  464. {
  465. parent = openCurrentMenu.BarItems;
  466. mi = parent.Children [openCurrentMenu._currentChild];
  467. }
  468. else if (openCurrentMenu!.BarItems.IsTopLevel)
  469. {
  470. parent = null;
  471. mi = openCurrentMenu.BarItems;
  472. }
  473. else
  474. {
  475. parent = _openMenu.BarItems;
  476. mi = parent.Children?.Length > 0 ? parent.Children [_openMenu._currentChild] : null;
  477. }
  478. MenuOpened?.Invoke (this, new MenuOpenedEventArgs (parent, mi));
  479. }
  480. /// <summary>Virtual method that will invoke the <see cref="MenuOpening"/> event if it's defined.</summary>
  481. /// <param name="currentMenu">The current menu to be replaced.</param>
  482. /// <returns>Returns the <see cref="MenuOpeningEventArgs"/></returns>
  483. public virtual MenuOpeningEventArgs OnMenuOpening (MenuBarItem currentMenu)
  484. {
  485. var ev = new MenuOpeningEventArgs (currentMenu);
  486. MenuOpening?.Invoke (this, ev);
  487. return ev;
  488. }
  489. /// <summary>Opens the Menu programatically, as though the F9 key were pressed.</summary>
  490. public void OpenMenu ()
  491. {
  492. MenuBar mbar = GetMouseGrabViewInstance (this);
  493. if (mbar is { })
  494. {
  495. mbar.CleanUp ();
  496. }
  497. if (!Enabled || _openMenu is { })
  498. {
  499. return;
  500. }
  501. _selected = 0;
  502. SetNeedsDisplay ();
  503. _previousFocused = SuperView is null ? Application.Current.Focused : SuperView.Focused;
  504. OpenMenu (_selected);
  505. if (!SelectEnabledItem (
  506. openCurrentMenu.BarItems.Children,
  507. openCurrentMenu._currentChild,
  508. out openCurrentMenu._currentChild
  509. )
  510. && !CloseMenu (false))
  511. {
  512. return;
  513. }
  514. if (!openCurrentMenu.CheckSubMenu ())
  515. {
  516. return;
  517. }
  518. Application.GrabMouse (this);
  519. }
  520. /// <inheritdoc/>
  521. public override void PositionCursor ()
  522. {
  523. if (_selected == -1 && HasFocus && Menus.Length > 0)
  524. {
  525. _selected = 0;
  526. }
  527. var pos = 0;
  528. for (var i = 0; i < Menus.Length; i++)
  529. {
  530. if (i == _selected)
  531. {
  532. pos++;
  533. Move (pos + 1, 0);
  534. return;
  535. }
  536. pos += _leftPadding
  537. + Menus [i].TitleLength
  538. + (Menus [i].Help.GetColumns () > 0
  539. ? Menus [i].Help.GetColumns () + _parensAroundHelp
  540. : 0)
  541. + _rightPadding;
  542. }
  543. }
  544. // Activates the menu, handles either first focus, or activating an entry when it was already active
  545. // For mouse events.
  546. internal void Activate (int idx, int sIdx = -1, MenuBarItem subMenu = null)
  547. {
  548. _selected = idx;
  549. _selectedSub = sIdx;
  550. if (_openMenu is null)
  551. {
  552. _previousFocused = SuperView is null ? Application.Current?.Focused ?? null : SuperView.Focused;
  553. }
  554. OpenMenu (idx, sIdx, subMenu);
  555. SetNeedsDisplay ();
  556. }
  557. internal void AltKeyUpHandler (Key e)
  558. {
  559. if (e.KeyCode == KeyCode.AltMask)
  560. {
  561. e.Handled = true;
  562. // User pressed Alt
  563. if (!IsMenuOpen && _openMenu is null && !_openedByAltKey)
  564. {
  565. // There's no open menu, the first menu item should be highlighted.
  566. // The right way to do this is to SetFocus(MenuBar), but for some reason
  567. // that faults.
  568. GetMouseGrabViewInstance (this)?.CleanUp ();
  569. IsMenuOpen = true;
  570. _openedByAltKey = true;
  571. _selected = 0;
  572. CanFocus = true;
  573. _lastFocused = SuperView == null
  574. ? Application.Current.MostFocused
  575. : SuperView.MostFocused;
  576. SetFocus ();
  577. SetNeedsDisplay ();
  578. Application.GrabMouse (this);
  579. }
  580. else if (!_openedByHotKey)
  581. {
  582. // There's an open menu. Close it.
  583. CleanUp ();
  584. }
  585. else
  586. {
  587. _openedByAltKey = false;
  588. _openedByHotKey = false;
  589. }
  590. }
  591. }
  592. internal void CleanUp ()
  593. {
  594. _isCleaning = true;
  595. if (_openMenu is { })
  596. {
  597. CloseAllMenus ();
  598. }
  599. _openedByAltKey = false;
  600. _openedByHotKey = false;
  601. IsMenuOpen = false;
  602. _selected = -1;
  603. CanFocus = _initialCanFocus;
  604. if (_lastFocused is { })
  605. {
  606. _lastFocused.SetFocus ();
  607. }
  608. SetNeedsDisplay ();
  609. Application.UngrabMouse ();
  610. _isCleaning = false;
  611. }
  612. internal void CloseAllMenus ()
  613. {
  614. if (!_isMenuOpening && !_isMenuClosing)
  615. {
  616. if (_openSubMenu is { } && !CloseMenu (false, true, true))
  617. {
  618. return;
  619. }
  620. if (!CloseMenu (false))
  621. {
  622. return;
  623. }
  624. if (LastFocused is { } && LastFocused != this)
  625. {
  626. _selected = -1;
  627. }
  628. Application.UngrabMouse ();
  629. }
  630. if (openCurrentMenu is { })
  631. {
  632. openCurrentMenu = null;
  633. }
  634. IsMenuOpen = false;
  635. _openedByAltKey = false;
  636. _openedByHotKey = false;
  637. OnMenuAllClosed ();
  638. }
  639. internal bool CloseMenu (bool reopen = false, bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  640. {
  641. MenuBarItem mbi = isSubMenu ? openCurrentMenu.BarItems : _openMenu?.BarItems;
  642. if (UseSubMenusSingleFrame && mbi is { } && !ignoreUseSubMenusSingleFrame && mbi.Parent is { })
  643. {
  644. return false;
  645. }
  646. _isMenuClosing = true;
  647. _reopen = reopen;
  648. MenuClosingEventArgs args = OnMenuClosing (mbi, reopen, isSubMenu);
  649. if (args.Cancel)
  650. {
  651. _isMenuClosing = false;
  652. if (args.CurrentMenu.Parent is { })
  653. {
  654. _openMenu._currentChild =
  655. ((MenuBarItem)args.CurrentMenu.Parent).Children.IndexOf (args.CurrentMenu);
  656. }
  657. return false;
  658. }
  659. switch (isSubMenu)
  660. {
  661. case false:
  662. if (_openMenu is { })
  663. {
  664. Application.Current.Remove (_openMenu);
  665. }
  666. SetNeedsDisplay ();
  667. if (_previousFocused is { } && _previousFocused is Menu && _openMenu is { } && _previousFocused.ToString () != openCurrentMenu.ToString ())
  668. {
  669. _previousFocused.SetFocus ();
  670. }
  671. _openMenu?.Dispose ();
  672. _openMenu = null;
  673. if (_lastFocused is Menu || _lastFocused is MenuBar)
  674. {
  675. _lastFocused = null;
  676. }
  677. LastFocused = _lastFocused;
  678. _lastFocused = null;
  679. if (LastFocused is { } && LastFocused.CanFocus)
  680. {
  681. if (!reopen)
  682. {
  683. _selected = -1;
  684. }
  685. if (_openSubMenu is { })
  686. {
  687. _openSubMenu = null;
  688. }
  689. if (openCurrentMenu is { })
  690. {
  691. Application.Current.Remove (openCurrentMenu);
  692. openCurrentMenu.Dispose ();
  693. openCurrentMenu = null;
  694. }
  695. LastFocused.SetFocus ();
  696. }
  697. else if (_openSubMenu is null || _openSubMenu.Count == 0)
  698. {
  699. CloseAllMenus ();
  700. }
  701. else
  702. {
  703. SetFocus ();
  704. PositionCursor ();
  705. }
  706. IsMenuOpen = false;
  707. break;
  708. case true:
  709. _selectedSub = -1;
  710. SetNeedsDisplay ();
  711. RemoveAllOpensSubMenus ();
  712. openCurrentMenu._previousSubFocused.SetFocus ();
  713. _openSubMenu = null;
  714. IsMenuOpen = true;
  715. break;
  716. }
  717. _reopen = false;
  718. _isMenuClosing = false;
  719. return true;
  720. }
  721. /// <summary>Gets the superview location offset relative to the <see cref="ConsoleDriver"/> location.</summary>
  722. /// <returns>The location offset.</returns>
  723. internal Point GetScreenOffset ()
  724. {
  725. if (Driver is null)
  726. {
  727. return Point.Empty;
  728. }
  729. Rect superViewFrame = SuperView is null ? Driver.Bounds : SuperView.Frame;
  730. View sv = SuperView is null ? Application.Current : SuperView;
  731. Point boundsOffset = sv.GetBoundsOffset ();
  732. return new Point (
  733. superViewFrame.X - sv.Frame.X - boundsOffset.X,
  734. superViewFrame.Y - sv.Frame.Y - boundsOffset.Y
  735. );
  736. }
  737. /// <summary>
  738. /// Gets the <see cref="Application.Current"/> location offset relative to the <see cref="ConsoleDriver"/>
  739. /// location.
  740. /// </summary>
  741. /// <returns>The location offset.</returns>
  742. internal Point GetScreenOffsetFromCurrent ()
  743. {
  744. Rect screen = Driver.Bounds;
  745. Rect currentFrame = Application.Current.Frame;
  746. Point boundsOffset = Application.Top.GetBoundsOffset ();
  747. return new Point (screen.X - currentFrame.X - boundsOffset.X, screen.Y - currentFrame.Y - boundsOffset.Y);
  748. }
  749. internal void NextMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  750. {
  751. switch (isSubMenu)
  752. {
  753. case false:
  754. if (_selected == -1)
  755. {
  756. _selected = 0;
  757. }
  758. else if (_selected + 1 == Menus.Length)
  759. {
  760. _selected = 0;
  761. }
  762. else
  763. {
  764. _selected++;
  765. }
  766. if (_selected > -1 && !CloseMenu (true, ignoreUseSubMenusSingleFrame))
  767. {
  768. return;
  769. }
  770. OpenMenu (_selected);
  771. SelectEnabledItem (
  772. openCurrentMenu.BarItems.Children,
  773. openCurrentMenu._currentChild,
  774. out openCurrentMenu._currentChild
  775. );
  776. break;
  777. case true:
  778. if (UseKeysUpDownAsKeysLeftRight)
  779. {
  780. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame))
  781. {
  782. NextMenu (false, ignoreUseSubMenusSingleFrame);
  783. }
  784. }
  785. else
  786. {
  787. MenuBarItem subMenu = openCurrentMenu._currentChild > -1 && openCurrentMenu.BarItems.Children.Length > 0
  788. ? openCurrentMenu.BarItems.SubMenu (
  789. openCurrentMenu.BarItems.Children [openCurrentMenu._currentChild]
  790. )
  791. : null;
  792. if ((_selectedSub == -1 || _openSubMenu is null || _openSubMenu?.Count - 1 == _selectedSub) && subMenu is null)
  793. {
  794. if (_openSubMenu is { } && !CloseMenu (false, true))
  795. {
  796. return;
  797. }
  798. NextMenu (false, ignoreUseSubMenusSingleFrame);
  799. }
  800. else if (subMenu != null
  801. || (openCurrentMenu._currentChild > -1
  802. && !openCurrentMenu.BarItems
  803. .Children [openCurrentMenu._currentChild]
  804. .IsFromSubMenu))
  805. {
  806. _selectedSub++;
  807. openCurrentMenu.CheckSubMenu ();
  808. }
  809. else
  810. {
  811. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame))
  812. {
  813. NextMenu (false, ignoreUseSubMenusSingleFrame);
  814. }
  815. return;
  816. }
  817. SetNeedsDisplay ();
  818. if (UseKeysUpDownAsKeysLeftRight)
  819. {
  820. openCurrentMenu.CheckSubMenu ();
  821. }
  822. }
  823. break;
  824. }
  825. }
  826. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem subMenu = null)
  827. {
  828. _isMenuOpening = true;
  829. MenuOpeningEventArgs newMenu = OnMenuOpening (Menus [index]);
  830. if (newMenu.Cancel)
  831. {
  832. _isMenuOpening = false;
  833. return;
  834. }
  835. if (newMenu.NewMenuBarItem is { })
  836. {
  837. Menus [index] = newMenu.NewMenuBarItem;
  838. }
  839. var pos = 0;
  840. switch (subMenu)
  841. {
  842. case null:
  843. // Open a submenu below a MenuBar
  844. _lastFocused ??= SuperView is null ? Application.Current?.MostFocused : SuperView.MostFocused;
  845. if (_openSubMenu is { } && !CloseMenu (false, true))
  846. {
  847. return;
  848. }
  849. if (_openMenu is { })
  850. {
  851. Application.Current.Remove (_openMenu);
  852. _openMenu.Dispose ();
  853. _openMenu = null;
  854. }
  855. // This positions the submenu horizontally aligned with the first character of the
  856. // text belonging to the menu
  857. for (var i = 0; i < index; i++)
  858. {
  859. pos += Menus [i].TitleLength + (Menus [i].Help.GetColumns () > 0 ? Menus [i].Help.GetColumns () + 2 : 0) + _leftPadding + _rightPadding;
  860. }
  861. var locationOffset = Point.Empty;
  862. // if SuperView is null then it's from a ContextMenu
  863. if (SuperView is null)
  864. {
  865. locationOffset = GetScreenOffset ();
  866. }
  867. if (SuperView is { } && SuperView != Application.Current)
  868. {
  869. locationOffset.X += SuperView.Border.Thickness.Left;
  870. locationOffset.Y += SuperView.Border.Thickness.Top;
  871. }
  872. _openMenu = new Menu
  873. {
  874. Host = this,
  875. X = Frame.X + pos + locationOffset.X,
  876. Y = Frame.Y + 1 + locationOffset.Y,
  877. BarItems = Menus [index],
  878. Parent = null
  879. };
  880. openCurrentMenu = _openMenu;
  881. openCurrentMenu._previousSubFocused = _openMenu;
  882. Application.Current.Add (_openMenu);
  883. _openMenu.SetFocus ();
  884. break;
  885. default:
  886. // Opens a submenu next to another submenu (openSubMenu)
  887. if (_openSubMenu is null)
  888. {
  889. _openSubMenu = new List<Menu> ();
  890. }
  891. if (sIndex > -1)
  892. {
  893. RemoveSubMenu (sIndex);
  894. }
  895. else
  896. {
  897. Menu last = _openSubMenu.Count > 0 ? _openSubMenu.Last () : _openMenu;
  898. if (!UseSubMenusSingleFrame)
  899. {
  900. locationOffset = GetLocationOffset ();
  901. openCurrentMenu = new Menu
  902. {
  903. Host = this,
  904. X = last.Frame.Left + last.Frame.Width + locationOffset.X,
  905. Y = last.Frame.Top + locationOffset.Y + last._currentChild,
  906. BarItems = subMenu,
  907. Parent = last
  908. };
  909. }
  910. else
  911. {
  912. Menu first = _openSubMenu.Count > 0 ? _openSubMenu.First () : _openMenu;
  913. // 2 is for the parent and the separator
  914. MenuItem [] mbi = new MenuItem [2 + subMenu.Children.Length];
  915. mbi [0] = new MenuItem { Title = subMenu.Title, Parent = subMenu };
  916. mbi [1] = null;
  917. for (var j = 0; j < subMenu.Children.Length; j++)
  918. {
  919. mbi [j + 2] = subMenu.Children [j];
  920. }
  921. var newSubMenu = new MenuBarItem (mbi) { Parent = subMenu };
  922. openCurrentMenu = new Menu
  923. {
  924. Host = this, X = first.Frame.Left, Y = first.Frame.Top, BarItems = newSubMenu
  925. };
  926. last.Visible = false;
  927. Application.GrabMouse (openCurrentMenu);
  928. }
  929. openCurrentMenu._previousSubFocused = last._previousSubFocused;
  930. _openSubMenu.Add (openCurrentMenu);
  931. Application.Current.Add (openCurrentMenu);
  932. }
  933. _selectedSub = _openSubMenu.Count - 1;
  934. if (_selectedSub > -1
  935. && SelectEnabledItem (
  936. openCurrentMenu.BarItems.Children,
  937. openCurrentMenu._currentChild,
  938. out openCurrentMenu._currentChild
  939. ))
  940. {
  941. openCurrentMenu.SetFocus ();
  942. }
  943. break;
  944. }
  945. _isMenuOpening = false;
  946. IsMenuOpen = true;
  947. }
  948. internal void PreviousMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  949. {
  950. switch (isSubMenu)
  951. {
  952. case false:
  953. if (_selected <= 0)
  954. {
  955. _selected = Menus.Length - 1;
  956. }
  957. else
  958. {
  959. _selected--;
  960. }
  961. if (_selected > -1 && !CloseMenu (true, false, ignoreUseSubMenusSingleFrame))
  962. {
  963. return;
  964. }
  965. OpenMenu (_selected);
  966. if (!SelectEnabledItem (
  967. openCurrentMenu.BarItems.Children,
  968. openCurrentMenu._currentChild,
  969. out openCurrentMenu._currentChild,
  970. false
  971. ))
  972. {
  973. openCurrentMenu._currentChild = 0;
  974. }
  975. break;
  976. case true:
  977. if (_selectedSub > -1)
  978. {
  979. _selectedSub--;
  980. RemoveSubMenu (_selectedSub, ignoreUseSubMenusSingleFrame);
  981. SetNeedsDisplay ();
  982. }
  983. else
  984. {
  985. PreviousMenu ();
  986. }
  987. break;
  988. }
  989. }
  990. internal void RemoveAllOpensSubMenus ()
  991. {
  992. if (_openSubMenu is { })
  993. {
  994. foreach (Menu item in _openSubMenu)
  995. {
  996. Application.Current.Remove (item);
  997. item.Dispose ();
  998. }
  999. }
  1000. }
  1001. internal bool Run (Action action)
  1002. {
  1003. if (action is null)
  1004. {
  1005. return false;
  1006. }
  1007. Application.MainLoop.AddIdle (
  1008. () =>
  1009. {
  1010. action ();
  1011. return false;
  1012. }
  1013. );
  1014. return true;
  1015. }
  1016. internal bool SelectEnabledItem (
  1017. IEnumerable<MenuItem> chldren,
  1018. int current,
  1019. out int newCurrent,
  1020. bool forward = true
  1021. )
  1022. {
  1023. if (chldren is null)
  1024. {
  1025. newCurrent = -1;
  1026. return true;
  1027. }
  1028. IEnumerable<MenuItem> childrens;
  1029. if (forward)
  1030. {
  1031. childrens = chldren;
  1032. }
  1033. else
  1034. {
  1035. childrens = chldren.Reverse ();
  1036. }
  1037. int count;
  1038. if (forward)
  1039. {
  1040. count = -1;
  1041. }
  1042. else
  1043. {
  1044. count = childrens.Count ();
  1045. }
  1046. foreach (MenuItem child in childrens)
  1047. {
  1048. if (forward)
  1049. {
  1050. if (++count < current)
  1051. {
  1052. continue;
  1053. }
  1054. }
  1055. else
  1056. {
  1057. if (--count > current)
  1058. {
  1059. continue;
  1060. }
  1061. }
  1062. if (child is null || !child.IsEnabled ())
  1063. {
  1064. if (forward)
  1065. {
  1066. current++;
  1067. }
  1068. else
  1069. {
  1070. current--;
  1071. }
  1072. }
  1073. else
  1074. {
  1075. newCurrent = current;
  1076. return true;
  1077. }
  1078. }
  1079. newCurrent = -1;
  1080. return false;
  1081. }
  1082. /// <summary>Called when an item is selected; Runs the action.</summary>
  1083. /// <param name="item"></param>
  1084. internal bool SelectItem (MenuItem item)
  1085. {
  1086. if (item?.Action is null)
  1087. {
  1088. return false;
  1089. }
  1090. Application.UngrabMouse ();
  1091. CloseAllMenus ();
  1092. Application.Refresh ();
  1093. _openedByAltKey = true;
  1094. return Run (item?.Action);
  1095. }
  1096. private void CloseMenuBar ()
  1097. {
  1098. if (!CloseMenu (false))
  1099. {
  1100. return;
  1101. }
  1102. if (_openedByAltKey)
  1103. {
  1104. _openedByAltKey = false;
  1105. LastFocused?.SetFocus ();
  1106. }
  1107. SetNeedsDisplay ();
  1108. }
  1109. private Point GetLocationOffset ()
  1110. {
  1111. if (MenusBorderStyle != LineStyle.None)
  1112. {
  1113. return new Point (0, 1);
  1114. }
  1115. return new Point (-2, 0);
  1116. }
  1117. private void MenuBar_Added (object sender, SuperViewChangedEventArgs e)
  1118. {
  1119. _initialCanFocus = CanFocus;
  1120. Added -= MenuBar_Added;
  1121. }
  1122. private void MoveLeft ()
  1123. {
  1124. _selected--;
  1125. if (_selected < 0)
  1126. {
  1127. _selected = Menus.Length - 1;
  1128. }
  1129. OpenMenu (_selected);
  1130. SetNeedsDisplay ();
  1131. }
  1132. private void MoveRight ()
  1133. {
  1134. _selected = (_selected + 1) % Menus.Length;
  1135. OpenMenu (_selected);
  1136. SetNeedsDisplay ();
  1137. }
  1138. private void ProcessMenu (int i, MenuBarItem mi)
  1139. {
  1140. if (_selected < 0 && IsMenuOpen)
  1141. {
  1142. return;
  1143. }
  1144. if (mi.IsTopLevel)
  1145. {
  1146. BoundsToScreen (i, 0, out int rx, out int ry);
  1147. var menu = new Menu { Host = this, X = rx, Y = ry, BarItems = mi };
  1148. menu.Run (mi.Action);
  1149. menu.Dispose ();
  1150. }
  1151. else
  1152. {
  1153. Application.GrabMouse (this);
  1154. _selected = i;
  1155. OpenMenu (i);
  1156. if (!SelectEnabledItem (
  1157. openCurrentMenu.BarItems.Children,
  1158. openCurrentMenu._currentChild,
  1159. out openCurrentMenu._currentChild
  1160. )
  1161. && !CloseMenu (false))
  1162. {
  1163. return;
  1164. }
  1165. if (!openCurrentMenu.CheckSubMenu ())
  1166. {
  1167. return;
  1168. }
  1169. }
  1170. SetNeedsDisplay ();
  1171. }
  1172. private void RemoveSubMenu (int index, bool ignoreUseSubMenusSingleFrame = false)
  1173. {
  1174. if (_openSubMenu == null
  1175. || (UseSubMenusSingleFrame
  1176. && !ignoreUseSubMenusSingleFrame
  1177. && _openSubMenu.Count == 0))
  1178. {
  1179. return;
  1180. }
  1181. for (int i = _openSubMenu.Count - 1; i > index; i--)
  1182. {
  1183. _isMenuClosing = true;
  1184. Menu menu;
  1185. if (_openSubMenu.Count - 1 > 0)
  1186. {
  1187. menu = _openSubMenu [i - 1];
  1188. }
  1189. else
  1190. {
  1191. menu = _openMenu;
  1192. }
  1193. if (!menu.Visible)
  1194. {
  1195. menu.Visible = true;
  1196. }
  1197. openCurrentMenu = menu;
  1198. openCurrentMenu.SetFocus ();
  1199. if (_openSubMenu is { })
  1200. {
  1201. menu = _openSubMenu [i];
  1202. Application.Current.Remove (menu);
  1203. _openSubMenu.Remove (menu);
  1204. menu.Dispose ();
  1205. }
  1206. RemoveSubMenu (i, ignoreUseSubMenusSingleFrame);
  1207. }
  1208. if (_openSubMenu.Count > 0)
  1209. {
  1210. openCurrentMenu = _openSubMenu.Last ();
  1211. }
  1212. _isMenuClosing = false;
  1213. }
  1214. #region Keyboard handling
  1215. private Key _key = Key.F9;
  1216. /// <summary>
  1217. /// The <see cref="Key"/> used to activate or close the menu bar by keyboard. The default is <see cref="Key.F9"/>
  1218. /// .
  1219. /// </summary>
  1220. /// <remarks>
  1221. /// <para>
  1222. /// If the user presses any <see cref="MenuItem.HotKey"/>s defined in the <see cref="MenuBarItem"/>s, the menu
  1223. /// bar will be activated and the sub-menu will be opened.
  1224. /// </para>
  1225. /// <para><see cref="Key.Esc"/> will close the menu bar and any open sub-menus.</para>
  1226. /// </remarks>
  1227. public Key Key
  1228. {
  1229. get => _key;
  1230. set
  1231. {
  1232. if (_key == value)
  1233. {
  1234. return;
  1235. }
  1236. KeyBindings.Remove (_key);
  1237. KeyBindings.Add (value, KeyBindingScope.HotKey, Command.ToggleExpandCollapse);
  1238. _key = value;
  1239. }
  1240. }
  1241. private bool _useKeysUpDownAsKeysLeftRight;
  1242. /// <summary>Used for change the navigation key style.</summary>
  1243. public bool UseKeysUpDownAsKeysLeftRight
  1244. {
  1245. get => _useKeysUpDownAsKeysLeftRight;
  1246. set
  1247. {
  1248. _useKeysUpDownAsKeysLeftRight = value;
  1249. if (value && UseSubMenusSingleFrame)
  1250. {
  1251. UseSubMenusSingleFrame = false;
  1252. SetNeedsDisplay ();
  1253. }
  1254. }
  1255. }
  1256. private static Rune _shortcutDelimiter = new ('+');
  1257. /// <summary>Sets or gets the shortcut delimiter separator. The default is "+".</summary>
  1258. public static Rune ShortcutDelimiter
  1259. {
  1260. get => _shortcutDelimiter;
  1261. set
  1262. {
  1263. if (_shortcutDelimiter != value)
  1264. {
  1265. _shortcutDelimiter = value == default (Rune) ? new Rune ('+') : value;
  1266. }
  1267. }
  1268. }
  1269. /// <summary>The specifier character for the hot keys.</summary>
  1270. public new static Rune HotKeySpecifier => (Rune)'_';
  1271. // Set in OnInvokingKeyBindings. -1 means no menu item is selected for activation.
  1272. private int _menuBarItemToActivate;
  1273. // Set in OnInvokingKeyBindings. null means no sub-menu is selected for activation.
  1274. private MenuItem _menuItemToSelect;
  1275. private bool _openedByAltKey;
  1276. private bool _openedByHotKey;
  1277. /// <summary>
  1278. /// Called when a key bound to Command.Select is pressed. Either activates the menu item or runs it, depending on
  1279. /// whether it has a sub-menu. If the menu is open, it will close the menu bar.
  1280. /// </summary>
  1281. /// <returns></returns>
  1282. private bool SelectOrRun ()
  1283. {
  1284. if (!IsInitialized || !Visible)
  1285. {
  1286. return true;
  1287. }
  1288. _openedByHotKey = true;
  1289. if (_menuBarItemToActivate != -1)
  1290. {
  1291. Activate (_menuBarItemToActivate);
  1292. }
  1293. else if (_menuItemToSelect is { })
  1294. {
  1295. Run (_menuItemToSelect.Action);
  1296. }
  1297. else
  1298. {
  1299. if (IsMenuOpen && _openMenu is { })
  1300. {
  1301. CloseAllMenus ();
  1302. }
  1303. else
  1304. {
  1305. OpenMenu ();
  1306. }
  1307. }
  1308. return true;
  1309. }
  1310. /// <inheritdoc/>
  1311. public override bool? OnInvokingKeyBindings (Key keyEvent)
  1312. {
  1313. // This is a bit of a hack. We want to handle the key bindings for menu bar but
  1314. // InvokeKeyBindings doesn't pass any context so we can't tell which item it is for.
  1315. // So before we call the base class we set SelectedItem appropriately.
  1316. // TODO: Figure out if there's a way to have KeyBindings pass context instead. Maybe a KeyBindingContext property?
  1317. KeyCode key = keyEvent.KeyCode;
  1318. if (KeyBindings.TryGet (key, out _))
  1319. {
  1320. _menuBarItemToActivate = -1;
  1321. _menuItemToSelect = null;
  1322. // Search for shortcuts first. If there's a shortcut, we don't want to activate the menu item.
  1323. for (var i = 0; i < Menus.Length; i++)
  1324. {
  1325. // Recurse through the menu to find one with the shortcut.
  1326. if (FindShortcutInChildMenu (key, Menus [i], out _menuItemToSelect))
  1327. {
  1328. _menuBarItemToActivate = i;
  1329. keyEvent.Scope = KeyBindingScope.HotKey;
  1330. return base.OnInvokingKeyBindings (keyEvent);
  1331. }
  1332. // Now see if any of the menu bar items have a hot key that matches
  1333. // Technically this is not possible because menu bar items don't have
  1334. // shortcuts or Actions. But it's here for completeness.
  1335. KeyCode? shortcut = Menus [i]?.Shortcut;
  1336. if (key == shortcut)
  1337. {
  1338. throw new InvalidOperationException ("Menu bar items cannot have shortcuts");
  1339. }
  1340. }
  1341. // Search for hot keys next.
  1342. for (var i = 0; i < Menus.Length; i++)
  1343. {
  1344. if (IsMenuOpen)
  1345. {
  1346. // We don't need to do anything because `Menu` will handle the key binding.
  1347. //break;
  1348. }
  1349. // No submenu item matched (or the menu is closed)
  1350. // Check if one of the menu bar item has a hot key that matches
  1351. int hotKeyValue = Menus [i]?.HotKey.Value ?? default (int);
  1352. var hotKey = (KeyCode)hotKeyValue;
  1353. if (hotKey != KeyCode.Null)
  1354. {
  1355. bool matches = key == hotKey || key == (hotKey | KeyCode.AltMask);
  1356. if (IsMenuOpen)
  1357. {
  1358. // If the menu is open, only match if Alt is not pressed.
  1359. matches = key == hotKey;
  1360. }
  1361. if (matches)
  1362. {
  1363. _menuBarItemToActivate = i;
  1364. keyEvent.Scope = KeyBindingScope.HotKey;
  1365. break;
  1366. }
  1367. }
  1368. }
  1369. }
  1370. return base.OnInvokingKeyBindings (keyEvent);
  1371. }
  1372. // TODO: Update to use Key instead of KeyCode
  1373. // Recurse the child menus looking for a shortcut that matches the key
  1374. private bool FindShortcutInChildMenu (KeyCode key, MenuBarItem menuBarItem, out MenuItem menuItemToSelect)
  1375. {
  1376. menuItemToSelect = null;
  1377. if (key == KeyCode.Null || menuBarItem?.Children is null)
  1378. {
  1379. return false;
  1380. }
  1381. for (var c = 0; c < menuBarItem.Children.Length; c++)
  1382. {
  1383. MenuItem menuItem = menuBarItem.Children [c];
  1384. if (key == menuItem?.Shortcut)
  1385. {
  1386. menuItemToSelect = menuItem;
  1387. return true;
  1388. }
  1389. MenuBarItem subMenu = menuBarItem.SubMenu (menuItem);
  1390. if (subMenu is { })
  1391. {
  1392. if (FindShortcutInChildMenu (key, subMenu, out menuItemToSelect))
  1393. {
  1394. return true;
  1395. }
  1396. }
  1397. }
  1398. return false;
  1399. }
  1400. #endregion Keyboard handling
  1401. #region Mouse Handling
  1402. /// <inheritdoc/>
  1403. public override bool OnEnter (View view)
  1404. {
  1405. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  1406. return base.OnEnter (view);
  1407. }
  1408. /// <inheritdoc/>
  1409. public override bool OnLeave (View view)
  1410. {
  1411. if (((!(view is MenuBar) && !(view is Menu)) || (!(view is MenuBar) && !(view is Menu) && _openMenu is { })) && !_isCleaning && !_reopen)
  1412. {
  1413. CleanUp ();
  1414. }
  1415. return base.OnLeave (view);
  1416. }
  1417. /// <inheritdoc/>
  1418. public override bool MouseEvent (MouseEvent me)
  1419. {
  1420. if (!_handled && !HandleGrabView (me, this))
  1421. {
  1422. return false;
  1423. }
  1424. _handled = false;
  1425. if (me.Flags == MouseFlags.Button1Pressed
  1426. || me.Flags == MouseFlags.Button1DoubleClicked
  1427. || me.Flags == MouseFlags.Button1TripleClicked
  1428. || me.Flags == MouseFlags.Button1Clicked
  1429. || (me.Flags == MouseFlags.ReportMousePosition && _selected > -1)
  1430. || (me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && _selected > -1))
  1431. {
  1432. int pos = _xOrigin;
  1433. Point locationOffset = default;
  1434. if (SuperView is { })
  1435. {
  1436. locationOffset.X += SuperView.Border.Thickness.Left;
  1437. locationOffset.Y += SuperView.Border.Thickness.Top;
  1438. }
  1439. int cx = me.X - locationOffset.X;
  1440. for (var i = 0; i < Menus.Length; i++)
  1441. {
  1442. if (cx >= pos && cx < pos + _leftPadding + Menus [i].TitleLength + Menus [i].Help.GetColumns () + _rightPadding)
  1443. {
  1444. if (me.Flags == MouseFlags.Button1Clicked)
  1445. {
  1446. if (Menus [i].IsTopLevel)
  1447. {
  1448. BoundsToScreen (i, 0, out int rx, out int ry);
  1449. var menu = new Menu { Host = this, X = rx, Y = ry, BarItems = Menus [i] };
  1450. menu.Run (Menus [i].Action);
  1451. menu.Dispose ();
  1452. }
  1453. else if (!IsMenuOpen)
  1454. {
  1455. Activate (i);
  1456. }
  1457. }
  1458. else if (me.Flags == MouseFlags.Button1Pressed
  1459. || me.Flags == MouseFlags.Button1DoubleClicked
  1460. || me.Flags == MouseFlags.Button1TripleClicked)
  1461. {
  1462. if (IsMenuOpen && !Menus [i].IsTopLevel)
  1463. {
  1464. CloseAllMenus ();
  1465. }
  1466. else if (!Menus [i].IsTopLevel)
  1467. {
  1468. Activate (i);
  1469. }
  1470. }
  1471. else if (_selected != i
  1472. && _selected > -1
  1473. && (me.Flags == MouseFlags.ReportMousePosition
  1474. || (me.Flags == MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)))
  1475. {
  1476. if (IsMenuOpen)
  1477. {
  1478. if (!CloseMenu (true, false))
  1479. {
  1480. return true;
  1481. }
  1482. Activate (i);
  1483. }
  1484. }
  1485. else if (IsMenuOpen)
  1486. {
  1487. if (!UseSubMenusSingleFrame
  1488. || (UseSubMenusSingleFrame
  1489. && openCurrentMenu != null
  1490. && openCurrentMenu.BarItems.Parent != null
  1491. && openCurrentMenu.BarItems.Parent.Parent != Menus [i]))
  1492. {
  1493. Activate (i);
  1494. }
  1495. }
  1496. return true;
  1497. }
  1498. if (i == Menus.Length - 1 && me.Flags == MouseFlags.Button1Clicked)
  1499. {
  1500. if (IsMenuOpen && !Menus [i].IsTopLevel)
  1501. {
  1502. CloseAllMenus ();
  1503. return true;
  1504. }
  1505. }
  1506. pos += _leftPadding + Menus [i].TitleLength + _rightPadding;
  1507. }
  1508. }
  1509. return false;
  1510. }
  1511. internal bool _handled;
  1512. internal bool _isContextMenuLoading;
  1513. private MenuBarItem [] _menus;
  1514. internal bool HandleGrabView (MouseEvent me, View current)
  1515. {
  1516. if (Application.MouseGrabView is { })
  1517. {
  1518. if (me.View is MenuBar || me.View is Menu)
  1519. {
  1520. MenuBar mbar = GetMouseGrabViewInstance (me.View);
  1521. if (mbar is { })
  1522. {
  1523. if (me.Flags == MouseFlags.Button1Clicked)
  1524. {
  1525. mbar.CleanUp ();
  1526. Application.GrabMouse (me.View);
  1527. }
  1528. else
  1529. {
  1530. _handled = false;
  1531. return false;
  1532. }
  1533. }
  1534. if (me.View != current)
  1535. {
  1536. Application.UngrabMouse ();
  1537. View v = me.View;
  1538. Application.GrabMouse (v);
  1539. MouseEvent nme;
  1540. if (me.Y > -1)
  1541. {
  1542. Point newxy = v.ScreenToFrame (me.X, me.Y);
  1543. nme = new MouseEvent
  1544. {
  1545. X = newxy.X,
  1546. Y = newxy.Y,
  1547. Flags = me.Flags,
  1548. OfX = me.X - newxy.X,
  1549. OfY = me.Y - newxy.Y,
  1550. View = v
  1551. };
  1552. }
  1553. else
  1554. {
  1555. nme = new MouseEvent { X = me.X + current.Frame.X, Y = 0, Flags = me.Flags, View = v };
  1556. }
  1557. v.MouseEvent (nme);
  1558. return false;
  1559. }
  1560. }
  1561. else if (!_isContextMenuLoading
  1562. && !(me.View is MenuBar || me.View is Menu)
  1563. && me.Flags != MouseFlags.ReportMousePosition
  1564. && me.Flags != 0)
  1565. {
  1566. Application.UngrabMouse ();
  1567. if (IsMenuOpen)
  1568. {
  1569. CloseAllMenus ();
  1570. }
  1571. _handled = false;
  1572. return false;
  1573. }
  1574. else
  1575. {
  1576. _handled = false;
  1577. _isContextMenuLoading = false;
  1578. return false;
  1579. }
  1580. }
  1581. else if (!IsMenuOpen
  1582. && (me.Flags == MouseFlags.Button1Pressed
  1583. || me.Flags == MouseFlags.Button1DoubleClicked
  1584. || me.Flags == MouseFlags.Button1TripleClicked
  1585. || me.Flags.HasFlag (
  1586. MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition
  1587. )))
  1588. {
  1589. Application.GrabMouse (current);
  1590. }
  1591. else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu))
  1592. {
  1593. Application.GrabMouse (me.View);
  1594. }
  1595. else
  1596. {
  1597. _handled = false;
  1598. return false;
  1599. }
  1600. _handled = true;
  1601. return true;
  1602. }
  1603. private MenuBar GetMouseGrabViewInstance (View view)
  1604. {
  1605. if (view is null || Application.MouseGrabView is null)
  1606. {
  1607. return null;
  1608. }
  1609. MenuBar hostView = null;
  1610. if (view is MenuBar)
  1611. {
  1612. hostView = (MenuBar)view;
  1613. }
  1614. else if (view is Menu)
  1615. {
  1616. hostView = ((Menu)view).Host;
  1617. }
  1618. View grabView = Application.MouseGrabView;
  1619. MenuBar hostGrabView = null;
  1620. if (grabView is MenuBar)
  1621. {
  1622. hostGrabView = (MenuBar)grabView;
  1623. }
  1624. else if (grabView is Menu)
  1625. {
  1626. hostGrabView = ((Menu)grabView).Host;
  1627. }
  1628. return hostView != hostGrabView ? hostGrabView : null;
  1629. }
  1630. #endregion Mouse Handling
  1631. }