MenuBar.cs 59 KB

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