MenuBar.cs 55 KB

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