MenuBar.cs 60 KB

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