MenuBar.cs 58 KB

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