MenuBar.cs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  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?.Focused : SuperView.Focused;
  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?.Focused ?? null : SuperView.Focused;
  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. if (Application.MouseGrabView is { } && Application.MouseGrabView is MenuBar && Application.MouseGrabView != this)
  403. {
  404. var menuBar = Application.MouseGrabView as MenuBar;
  405. if (menuBar!.IsMenuOpen)
  406. {
  407. menuBar.CleanUp ();
  408. }
  409. }
  410. Application.UngrabMouse ();
  411. _isCleaning = false;
  412. }
  413. internal void CloseAllMenus ()
  414. {
  415. if (!_isMenuOpening && !_isMenuClosing)
  416. {
  417. if (_openSubMenu is { } && !CloseMenu (false, true, true))
  418. {
  419. return;
  420. }
  421. if (!CloseMenu (false))
  422. {
  423. return;
  424. }
  425. if (LastFocused is { } && LastFocused != this)
  426. {
  427. _selected = -1;
  428. }
  429. Application.UngrabMouse ();
  430. }
  431. if (OpenCurrentMenu is { })
  432. {
  433. OpenCurrentMenu = null;
  434. }
  435. IsMenuOpen = false;
  436. _openedByAltKey = false;
  437. OnMenuAllClosed ();
  438. }
  439. internal bool CloseMenu (bool reopen = false, bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  440. {
  441. MenuBarItem mbi = isSubMenu ? OpenCurrentMenu.BarItems : _openMenu?.BarItems;
  442. if (UseSubMenusSingleFrame && mbi is { } && !ignoreUseSubMenusSingleFrame && mbi.Parent is { })
  443. {
  444. return false;
  445. }
  446. _isMenuClosing = true;
  447. _reopen = reopen;
  448. MenuClosingEventArgs args = OnMenuClosing (mbi, reopen, isSubMenu);
  449. if (args.Cancel)
  450. {
  451. _isMenuClosing = false;
  452. if (args.CurrentMenu.Parent is { } && _openMenu is { })
  453. {
  454. _openMenu._currentChild =
  455. ((MenuBarItem)args.CurrentMenu.Parent).Children.IndexOf (args.CurrentMenu);
  456. }
  457. return false;
  458. }
  459. switch (isSubMenu)
  460. {
  461. case false:
  462. if (_openMenu is { })
  463. {
  464. Application.Current?.Remove (_openMenu);
  465. }
  466. SetNeedsDisplay ();
  467. if (_previousFocused is Menu && _openMenu is { } && _previousFocused.ToString () != OpenCurrentMenu.ToString ())
  468. {
  469. _previousFocused.SetFocus ();
  470. }
  471. _openMenu?.Dispose ();
  472. _openMenu = null;
  473. if (_lastFocused is Menu or MenuBar)
  474. {
  475. _lastFocused = null;
  476. }
  477. LastFocused = _lastFocused;
  478. _lastFocused = null;
  479. if (LastFocused is { CanFocus: true })
  480. {
  481. if (!reopen)
  482. {
  483. _selected = -1;
  484. }
  485. if (_openSubMenu is { })
  486. {
  487. _openSubMenu = null;
  488. }
  489. if (OpenCurrentMenu is { })
  490. {
  491. Application.Current?.Remove (OpenCurrentMenu);
  492. OpenCurrentMenu.Dispose ();
  493. OpenCurrentMenu = null;
  494. }
  495. LastFocused.SetFocus ();
  496. }
  497. else if (_openSubMenu is null || _openSubMenu.Count == 0)
  498. {
  499. CloseAllMenus ();
  500. }
  501. else
  502. {
  503. SetFocus ();
  504. }
  505. IsMenuOpen = false;
  506. break;
  507. case true:
  508. _selectedSub = -1;
  509. SetNeedsDisplay ();
  510. RemoveAllOpensSubMenus ();
  511. OpenCurrentMenu._previousSubFocused.SetFocus ();
  512. _openSubMenu = null;
  513. IsMenuOpen = true;
  514. break;
  515. }
  516. _reopen = false;
  517. _isMenuClosing = false;
  518. return true;
  519. }
  520. /// <summary>Gets the superview location offset relative to the <see cref="ConsoleDriver"/> location.</summary>
  521. /// <returns>The location offset.</returns>
  522. internal Point GetScreenOffset ()
  523. {
  524. if (Driver is null)
  525. {
  526. return Point.Empty;
  527. }
  528. Rectangle superViewFrame = SuperView is null ? Application.Screen : SuperView.Frame;
  529. View sv = SuperView is null ? Application.Current : SuperView;
  530. if (sv is null)
  531. {
  532. // Support Unit Tests
  533. return Point.Empty;
  534. }
  535. Point viewportOffset = sv?.GetViewportOffsetFromFrame () ?? Point.Empty;
  536. return new (
  537. superViewFrame.X - sv.Frame.X - viewportOffset.X,
  538. superViewFrame.Y - sv.Frame.Y - viewportOffset.Y
  539. );
  540. }
  541. internal void NextMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  542. {
  543. switch (isSubMenu)
  544. {
  545. case false:
  546. if (_selected == -1)
  547. {
  548. _selected = 0;
  549. }
  550. else if (_selected + 1 == Menus.Length)
  551. {
  552. _selected = 0;
  553. }
  554. else
  555. {
  556. _selected++;
  557. }
  558. if (_selected > -1 && !CloseMenu (true, ignoreUseSubMenusSingleFrame))
  559. {
  560. return;
  561. }
  562. OpenMenu (_selected);
  563. SelectEnabledItem (
  564. OpenCurrentMenu.BarItems.Children,
  565. OpenCurrentMenu._currentChild,
  566. out OpenCurrentMenu._currentChild
  567. );
  568. break;
  569. case true:
  570. if (UseKeysUpDownAsKeysLeftRight)
  571. {
  572. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame))
  573. {
  574. NextMenu (false, ignoreUseSubMenusSingleFrame);
  575. }
  576. }
  577. else
  578. {
  579. MenuBarItem subMenu = OpenCurrentMenu._currentChild > -1 && OpenCurrentMenu.BarItems.Children.Length > 0
  580. ? OpenCurrentMenu.BarItems.SubMenu (
  581. OpenCurrentMenu.BarItems.Children [OpenCurrentMenu._currentChild]
  582. )
  583. : null;
  584. if ((_selectedSub == -1 || _openSubMenu is null || _openSubMenu?.Count - 1 == _selectedSub) && subMenu is null)
  585. {
  586. if (_openSubMenu is { } && !CloseMenu (false, true))
  587. {
  588. return;
  589. }
  590. NextMenu (false, ignoreUseSubMenusSingleFrame);
  591. }
  592. else if (subMenu != null
  593. || (OpenCurrentMenu._currentChild > -1
  594. && !OpenCurrentMenu.BarItems
  595. .Children [OpenCurrentMenu._currentChild]
  596. .IsFromSubMenu))
  597. {
  598. _selectedSub++;
  599. OpenCurrentMenu.CheckSubMenu ();
  600. }
  601. else
  602. {
  603. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame))
  604. {
  605. NextMenu (false, ignoreUseSubMenusSingleFrame);
  606. }
  607. return;
  608. }
  609. SetNeedsDisplay ();
  610. if (UseKeysUpDownAsKeysLeftRight)
  611. {
  612. OpenCurrentMenu.CheckSubMenu ();
  613. }
  614. }
  615. break;
  616. }
  617. }
  618. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem subMenu = null)
  619. {
  620. _isMenuOpening = true;
  621. MenuOpeningEventArgs newMenu = OnMenuOpening (Menus [index]);
  622. if (newMenu.Cancel)
  623. {
  624. _isMenuOpening = false;
  625. return;
  626. }
  627. if (newMenu.NewMenuBarItem is { })
  628. {
  629. Menus [index] = newMenu.NewMenuBarItem;
  630. }
  631. var pos = 0;
  632. switch (subMenu)
  633. {
  634. case null:
  635. // Open a submenu below a MenuBar
  636. _lastFocused ??= SuperView is null ? Application.Current?.MostFocused : SuperView.MostFocused;
  637. if (_openSubMenu is { } && !CloseMenu (false, true))
  638. {
  639. return;
  640. }
  641. if (_openMenu is { })
  642. {
  643. Application.Current?.Remove (_openMenu);
  644. _openMenu.Dispose ();
  645. _openMenu = null;
  646. }
  647. // This positions the submenu horizontally aligned with the first character of the
  648. // text belonging to the menu
  649. for (var i = 0; i < index; i++)
  650. {
  651. pos += Menus [i].TitleLength + (Menus [i].Help.GetColumns () > 0 ? Menus [i].Help.GetColumns () + 2 : 0) + _leftPadding + _rightPadding;
  652. }
  653. var locationOffset = Point.Empty;
  654. // if SuperView is null then it's from a ContextMenu
  655. if (SuperView is null)
  656. {
  657. locationOffset = GetScreenOffset ();
  658. }
  659. if (SuperView is { } && SuperView != Application.Current)
  660. {
  661. locationOffset.X += SuperView.Border.Thickness.Left;
  662. locationOffset.Y += SuperView.Border.Thickness.Top;
  663. }
  664. _openMenu = new ()
  665. {
  666. Host = this,
  667. X = Frame.X + pos + locationOffset.X,
  668. Y = Frame.Y + 1 + locationOffset.Y,
  669. BarItems = Menus [index],
  670. Parent = null
  671. };
  672. OpenCurrentMenu = _openMenu;
  673. OpenCurrentMenu._previousSubFocused = _openMenu;
  674. if (Application.Current is { })
  675. {
  676. Application.Current.Add (_openMenu);
  677. }
  678. else
  679. {
  680. _openMenu.BeginInit ();
  681. _openMenu.EndInit ();
  682. }
  683. _openMenu.SetFocus ();
  684. break;
  685. default:
  686. // Opens a submenu next to another submenu (openSubMenu)
  687. if (_openSubMenu is null)
  688. {
  689. _openSubMenu = new ();
  690. }
  691. if (sIndex > -1)
  692. {
  693. RemoveSubMenu (sIndex);
  694. }
  695. else
  696. {
  697. Menu last = _openSubMenu.Count > 0 ? _openSubMenu.Last () : _openMenu;
  698. if (!UseSubMenusSingleFrame)
  699. {
  700. locationOffset = GetLocationOffset ();
  701. OpenCurrentMenu = new ()
  702. {
  703. Host = this,
  704. X = last.Frame.Left + last.Frame.Width + locationOffset.X,
  705. Y = last.Frame.Top + locationOffset.Y + last._currentChild,
  706. BarItems = subMenu,
  707. Parent = last
  708. };
  709. }
  710. else
  711. {
  712. Menu first = _openSubMenu.Count > 0 ? _openSubMenu.First () : _openMenu;
  713. // 2 is for the parent and the separator
  714. MenuItem [] mbi = new MenuItem [2 + subMenu.Children.Length];
  715. mbi [0] = new () { Title = subMenu.Title, Parent = subMenu };
  716. mbi [1] = null;
  717. for (var j = 0; j < subMenu.Children.Length; j++)
  718. {
  719. mbi [j + 2] = subMenu.Children [j];
  720. }
  721. var newSubMenu = new MenuBarItem (mbi) { Parent = subMenu };
  722. OpenCurrentMenu = new ()
  723. {
  724. Host = this, X = first.Frame.Left, Y = first.Frame.Top, BarItems = newSubMenu
  725. };
  726. last.Visible = false;
  727. Application.GrabMouse (OpenCurrentMenu);
  728. }
  729. OpenCurrentMenu._previousSubFocused = last._previousSubFocused;
  730. _openSubMenu.Add (OpenCurrentMenu);
  731. Application.Current?.Add (OpenCurrentMenu);
  732. if (!OpenCurrentMenu.IsInitialized)
  733. {
  734. // Supports unit tests
  735. OpenCurrentMenu.BeginInit ();
  736. OpenCurrentMenu.EndInit ();
  737. }
  738. }
  739. _selectedSub = _openSubMenu.Count - 1;
  740. if (_selectedSub > -1
  741. && SelectEnabledItem (
  742. OpenCurrentMenu.BarItems.Children,
  743. OpenCurrentMenu._currentChild,
  744. out OpenCurrentMenu._currentChild
  745. ))
  746. {
  747. OpenCurrentMenu.SetFocus ();
  748. }
  749. break;
  750. }
  751. _isMenuOpening = false;
  752. IsMenuOpen = true;
  753. }
  754. internal void PreviousMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  755. {
  756. switch (isSubMenu)
  757. {
  758. case false:
  759. if (_selected <= 0)
  760. {
  761. _selected = Menus.Length - 1;
  762. }
  763. else
  764. {
  765. _selected--;
  766. }
  767. if (_selected > -1 && !CloseMenu (true, false, ignoreUseSubMenusSingleFrame))
  768. {
  769. return;
  770. }
  771. OpenMenu (_selected);
  772. if (!SelectEnabledItem (
  773. OpenCurrentMenu.BarItems.Children,
  774. OpenCurrentMenu._currentChild,
  775. out OpenCurrentMenu._currentChild,
  776. false
  777. ))
  778. {
  779. OpenCurrentMenu._currentChild = 0;
  780. }
  781. break;
  782. case true:
  783. if (_selectedSub > -1)
  784. {
  785. _selectedSub--;
  786. RemoveSubMenu (_selectedSub, ignoreUseSubMenusSingleFrame);
  787. SetNeedsDisplay ();
  788. }
  789. else
  790. {
  791. PreviousMenu ();
  792. }
  793. break;
  794. }
  795. }
  796. internal void RemoveAllOpensSubMenus ()
  797. {
  798. if (_openSubMenu is { })
  799. {
  800. foreach (Menu item in _openSubMenu)
  801. {
  802. Application.Current.Remove (item);
  803. item.Dispose ();
  804. }
  805. }
  806. }
  807. internal bool Run (Action action)
  808. {
  809. if (action is null)
  810. {
  811. return false;
  812. }
  813. Application.MainLoop.AddIdle (
  814. () =>
  815. {
  816. action ();
  817. return false;
  818. }
  819. );
  820. return true;
  821. }
  822. internal bool SelectEnabledItem (
  823. IEnumerable<MenuItem> children,
  824. int current,
  825. out int newCurrent,
  826. bool forward = true
  827. )
  828. {
  829. if (children is null)
  830. {
  831. newCurrent = -1;
  832. return true;
  833. }
  834. IEnumerable<MenuItem> childMenuItems = forward ? children : children.Reverse ();
  835. int count;
  836. IEnumerable<MenuItem> menuItems = childMenuItems as MenuItem [] ?? childMenuItems.ToArray ();
  837. if (forward)
  838. {
  839. count = -1;
  840. }
  841. else
  842. {
  843. count = menuItems.Count ();
  844. }
  845. foreach (MenuItem child in menuItems)
  846. {
  847. if (forward)
  848. {
  849. if (++count < current)
  850. {
  851. continue;
  852. }
  853. }
  854. else
  855. {
  856. if (--count > current)
  857. {
  858. continue;
  859. }
  860. }
  861. if (child is null || !child.IsEnabled ())
  862. {
  863. if (forward)
  864. {
  865. current++;
  866. }
  867. else
  868. {
  869. current--;
  870. }
  871. }
  872. else
  873. {
  874. newCurrent = current;
  875. return true;
  876. }
  877. }
  878. newCurrent = -1;
  879. return false;
  880. }
  881. /// <summary>Called when an item is selected; Runs the action.</summary>
  882. /// <param name="item"></param>
  883. internal bool SelectItem (MenuItem item)
  884. {
  885. if (item?.Action is null)
  886. {
  887. return false;
  888. }
  889. Application.UngrabMouse ();
  890. CloseAllMenus ();
  891. Application.Refresh ();
  892. _openedByAltKey = true;
  893. return Run (item?.Action);
  894. }
  895. private void CloseMenuBar ()
  896. {
  897. if (!CloseMenu (false))
  898. {
  899. return;
  900. }
  901. if (_openedByAltKey)
  902. {
  903. _openedByAltKey = false;
  904. LastFocused?.SetFocus ();
  905. }
  906. SetNeedsDisplay ();
  907. }
  908. private Point GetLocationOffset ()
  909. {
  910. if (MenusBorderStyle != LineStyle.None)
  911. {
  912. return new (0, 1);
  913. }
  914. return new (-2, 0);
  915. }
  916. private void MenuBar_Added (object sender, SuperViewChangedEventArgs e)
  917. {
  918. _initialCanFocus = CanFocus;
  919. Added -= MenuBar_Added;
  920. }
  921. private void MoveLeft ()
  922. {
  923. _selected--;
  924. if (_selected < 0)
  925. {
  926. _selected = Menus.Length - 1;
  927. }
  928. OpenMenu (_selected);
  929. SetNeedsDisplay ();
  930. }
  931. private void MoveRight ()
  932. {
  933. _selected = (_selected + 1) % Menus.Length;
  934. OpenMenu (_selected);
  935. SetNeedsDisplay ();
  936. }
  937. private void ProcessMenu (int i, MenuBarItem mi)
  938. {
  939. if (_selected < 0 && IsMenuOpen)
  940. {
  941. return;
  942. }
  943. if (mi.IsTopLevel)
  944. {
  945. Point screen = ViewportToScreen (new Point (0, i));
  946. var menu = new Menu { Host = this, X = screen.X, Y = screen.Y, BarItems = mi };
  947. menu.Run (mi.Action);
  948. menu.Dispose ();
  949. }
  950. else
  951. {
  952. Application.GrabMouse (this);
  953. _selected = i;
  954. OpenMenu (i);
  955. if (!SelectEnabledItem (
  956. OpenCurrentMenu.BarItems.Children,
  957. OpenCurrentMenu._currentChild,
  958. out OpenCurrentMenu._currentChild
  959. )
  960. && !CloseMenu (false))
  961. {
  962. return;
  963. }
  964. if (!OpenCurrentMenu.CheckSubMenu ())
  965. {
  966. return;
  967. }
  968. }
  969. SetNeedsDisplay ();
  970. }
  971. private void RemoveSubMenu (int index, bool ignoreUseSubMenusSingleFrame = false)
  972. {
  973. if (_openSubMenu == null
  974. || (UseSubMenusSingleFrame
  975. && !ignoreUseSubMenusSingleFrame
  976. && _openSubMenu.Count == 0))
  977. {
  978. return;
  979. }
  980. for (int i = _openSubMenu.Count - 1; i > index; i--)
  981. {
  982. _isMenuClosing = true;
  983. Menu menu;
  984. if (_openSubMenu.Count - 1 > 0)
  985. {
  986. menu = _openSubMenu [i - 1];
  987. }
  988. else
  989. {
  990. menu = _openMenu;
  991. }
  992. if (!menu.Visible)
  993. {
  994. menu.Visible = true;
  995. }
  996. OpenCurrentMenu = menu;
  997. OpenCurrentMenu.SetFocus ();
  998. if (_openSubMenu is { })
  999. {
  1000. menu = _openSubMenu [i];
  1001. Application.Current.Remove (menu);
  1002. _openSubMenu.Remove (menu);
  1003. if (Application.MouseGrabView == menu)
  1004. {
  1005. Application.GrabMouse (this);
  1006. }
  1007. menu.Dispose ();
  1008. }
  1009. RemoveSubMenu (i, ignoreUseSubMenusSingleFrame);
  1010. }
  1011. if (_openSubMenu.Count > 0)
  1012. {
  1013. OpenCurrentMenu = _openSubMenu.Last ();
  1014. }
  1015. _isMenuClosing = false;
  1016. }
  1017. #region Keyboard handling
  1018. private Key _key = Key.F9;
  1019. /// <summary>
  1020. /// The <see cref="Key"/> used to activate or close the menu bar by keyboard. The default is <see cref="Key.F9"/>
  1021. /// .
  1022. /// </summary>
  1023. /// <remarks>
  1024. /// <para>
  1025. /// If the user presses any <see cref="MenuItem.HotKey"/>s defined in the <see cref="MenuBarItem"/>s, the menu
  1026. /// bar will be activated and the sub-menu will be opened.
  1027. /// </para>
  1028. /// <para><see cref="Key.Esc"/> will close the menu bar and any open sub-menus.</para>
  1029. /// </remarks>
  1030. public Key Key
  1031. {
  1032. get => _key;
  1033. set
  1034. {
  1035. if (_key == value)
  1036. {
  1037. return;
  1038. }
  1039. KeyBindings.Remove (_key);
  1040. KeyBinding keyBinding = new ([Command.ToggleExpandCollapse], KeyBindingScope.HotKey, -1); // -1 indicates Key was used
  1041. KeyBindings.Add (value, keyBinding);
  1042. _key = value;
  1043. }
  1044. }
  1045. private bool _useKeysUpDownAsKeysLeftRight;
  1046. /// <summary>Used for change the navigation key style.</summary>
  1047. public bool UseKeysUpDownAsKeysLeftRight
  1048. {
  1049. get => _useKeysUpDownAsKeysLeftRight;
  1050. set
  1051. {
  1052. _useKeysUpDownAsKeysLeftRight = value;
  1053. if (value && UseSubMenusSingleFrame)
  1054. {
  1055. UseSubMenusSingleFrame = false;
  1056. SetNeedsDisplay ();
  1057. }
  1058. }
  1059. }
  1060. /// <summary>The specifier character for the hot keys.</summary>
  1061. public new static Rune HotKeySpecifier => (Rune)'_';
  1062. // TODO: This doesn't actually work. Figure out why.
  1063. private bool _openedByAltKey;
  1064. /// <summary>
  1065. /// Called when a key bound to Command.Select is pressed. Either activates the menu item or runs it, depending on
  1066. /// whether it has a sub-menu. If the menu is open, it will close the menu bar.
  1067. /// </summary>
  1068. /// <param name="index">The index of the menu bar item to select. -1 if the selection was via <see cref="Key"/>.</param>
  1069. /// <returns></returns>
  1070. private bool Select (int index)
  1071. {
  1072. if (!IsInitialized || !Visible)
  1073. {
  1074. return true;
  1075. }
  1076. // If the menubar is open and the menu that's open is 'index' then close it. Otherwise activate it.
  1077. if (IsMenuOpen)
  1078. {
  1079. if (index == -1)
  1080. {
  1081. CloseAllMenus ();
  1082. return true;
  1083. }
  1084. // Find the index of the open submenu and close the menu if it matches
  1085. for (var i = 0; i < Menus.Length; i++)
  1086. {
  1087. MenuBarItem open = Menus [i];
  1088. if (open is null)
  1089. {
  1090. continue;
  1091. }
  1092. if (open == OpenCurrentMenu.BarItems && i == index)
  1093. {
  1094. CloseAllMenus ();
  1095. return true;
  1096. }
  1097. }
  1098. }
  1099. if (index == -1)
  1100. {
  1101. OpenMenu ();
  1102. }
  1103. else if (Menus [index].IsTopLevel)
  1104. {
  1105. Run (Menus [index].Action);
  1106. }
  1107. else
  1108. {
  1109. Activate (index);
  1110. }
  1111. return true;
  1112. }
  1113. #endregion Keyboard handling
  1114. #region Mouse Handling
  1115. /// <inheritdoc/>
  1116. internal void LostFocus (View view)
  1117. {
  1118. if (((!(view is MenuBar) && !(view is Menu))) && !_isCleaning && !_reopen)
  1119. {
  1120. CleanUp ();
  1121. }
  1122. return;
  1123. }
  1124. /// <inheritdoc/>
  1125. protected internal override bool OnMouseEvent (MouseEvent me)
  1126. {
  1127. if (!_handled && !HandleGrabView (me, this))
  1128. {
  1129. return false;
  1130. }
  1131. _handled = false;
  1132. if (me.Flags == MouseFlags.Button1Pressed
  1133. || me.Flags == MouseFlags.Button1DoubleClicked
  1134. || me.Flags == MouseFlags.Button1TripleClicked
  1135. || me.Flags == MouseFlags.Button1Clicked
  1136. || (me.Flags == MouseFlags.ReportMousePosition && _selected > -1)
  1137. || (me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && _selected > -1))
  1138. {
  1139. int pos = _xOrigin;
  1140. Point locationOffset = default;
  1141. if (SuperView is { })
  1142. {
  1143. locationOffset.X += SuperView.Border.Thickness.Left;
  1144. locationOffset.Y += SuperView.Border.Thickness.Top;
  1145. }
  1146. int cx = me.Position.X - locationOffset.X;
  1147. for (var i = 0; i < Menus.Length; i++)
  1148. {
  1149. if (cx >= pos && cx < pos + _leftPadding + Menus [i].TitleLength + Menus [i].Help.GetColumns () + _rightPadding)
  1150. {
  1151. if (me.Flags == MouseFlags.Button1Clicked)
  1152. {
  1153. if (Menus [i].IsTopLevel)
  1154. {
  1155. Point screen = ViewportToScreen (new Point (0, i));
  1156. var menu = new Menu { Host = this, X = screen.X, Y = screen.Y, BarItems = Menus [i] };
  1157. menu.Run (Menus [i].Action);
  1158. menu.Dispose ();
  1159. }
  1160. else if (!IsMenuOpen)
  1161. {
  1162. Activate (i);
  1163. }
  1164. }
  1165. else if (me.Flags == MouseFlags.Button1Pressed
  1166. || me.Flags == MouseFlags.Button1DoubleClicked
  1167. || me.Flags == MouseFlags.Button1TripleClicked)
  1168. {
  1169. if (IsMenuOpen && !Menus [i].IsTopLevel)
  1170. {
  1171. CloseAllMenus ();
  1172. }
  1173. else if (!Menus [i].IsTopLevel)
  1174. {
  1175. Activate (i);
  1176. }
  1177. }
  1178. else if (_selected != i
  1179. && _selected > -1
  1180. && (me.Flags == MouseFlags.ReportMousePosition
  1181. || (me.Flags == MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)))
  1182. {
  1183. if (IsMenuOpen)
  1184. {
  1185. if (!CloseMenu (true, false))
  1186. {
  1187. return me.Handled = true;
  1188. }
  1189. Activate (i);
  1190. }
  1191. }
  1192. else if (IsMenuOpen)
  1193. {
  1194. if (!UseSubMenusSingleFrame
  1195. || (UseSubMenusSingleFrame
  1196. && OpenCurrentMenu != null
  1197. && OpenCurrentMenu.BarItems.Parent != null
  1198. && OpenCurrentMenu.BarItems.Parent.Parent != Menus [i]))
  1199. {
  1200. Activate (i);
  1201. }
  1202. }
  1203. return me.Handled = true;
  1204. }
  1205. if (i == Menus.Length - 1 && me.Flags == MouseFlags.Button1Clicked)
  1206. {
  1207. if (IsMenuOpen && !Menus [i].IsTopLevel)
  1208. {
  1209. CloseAllMenus ();
  1210. return me.Handled = true;
  1211. }
  1212. }
  1213. pos += _leftPadding + Menus [i].TitleLength + _rightPadding;
  1214. }
  1215. }
  1216. return false;
  1217. }
  1218. internal bool _handled;
  1219. internal bool _isContextMenuLoading;
  1220. private MenuBarItem [] _menus;
  1221. internal bool HandleGrabView (MouseEvent me, View current)
  1222. {
  1223. if (Application.MouseGrabView is { })
  1224. {
  1225. if (me.View is MenuBar || me.View is Menu)
  1226. {
  1227. MenuBar mbar = GetMouseGrabViewInstance (me.View);
  1228. if (mbar is { })
  1229. {
  1230. if (me.Flags == MouseFlags.Button1Clicked)
  1231. {
  1232. mbar.CleanUp ();
  1233. Application.GrabMouse (me.View);
  1234. }
  1235. else
  1236. {
  1237. _handled = false;
  1238. return false;
  1239. }
  1240. }
  1241. if (me.View != current)
  1242. {
  1243. Application.UngrabMouse ();
  1244. View v = me.View;
  1245. Application.GrabMouse (v);
  1246. MouseEvent nme;
  1247. if (me.Position.Y > -1)
  1248. {
  1249. Point frameLoc = v.ScreenToFrame (me.Position);
  1250. nme = new ()
  1251. {
  1252. Position = frameLoc,
  1253. Flags = me.Flags,
  1254. View = v
  1255. };
  1256. }
  1257. else
  1258. {
  1259. nme = new ()
  1260. {
  1261. Position = new (me.Position.X + current.Frame.X, me.Position.Y + current.Frame.Y),
  1262. Flags = me.Flags, View = v
  1263. };
  1264. }
  1265. v.NewMouseEvent (nme);
  1266. return false;
  1267. }
  1268. }
  1269. else if (!(me.View is MenuBar || me.View is Menu)
  1270. && me.Flags != MouseFlags.ReportMousePosition
  1271. && me.Flags != 0)
  1272. {
  1273. Application.UngrabMouse ();
  1274. if (IsMenuOpen)
  1275. {
  1276. CloseAllMenus ();
  1277. }
  1278. _handled = false;
  1279. return false;
  1280. }
  1281. else
  1282. {
  1283. _handled = false;
  1284. _isContextMenuLoading = false;
  1285. return false;
  1286. }
  1287. }
  1288. else if (!IsMenuOpen
  1289. && (me.Flags == MouseFlags.Button1Pressed
  1290. || me.Flags == MouseFlags.Button1DoubleClicked
  1291. || me.Flags == MouseFlags.Button1TripleClicked
  1292. || me.Flags.HasFlag (
  1293. MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition
  1294. )))
  1295. {
  1296. Application.GrabMouse (current);
  1297. }
  1298. else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu))
  1299. {
  1300. Application.GrabMouse (me.View);
  1301. }
  1302. else
  1303. {
  1304. _handled = false;
  1305. return false;
  1306. }
  1307. _handled = true;
  1308. return true;
  1309. }
  1310. private MenuBar GetMouseGrabViewInstance (View view)
  1311. {
  1312. if (view is null || Application.MouseGrabView is null)
  1313. {
  1314. return null;
  1315. }
  1316. MenuBar hostView = null;
  1317. if (view is MenuBar)
  1318. {
  1319. hostView = (MenuBar)view;
  1320. }
  1321. else if (view is Menu)
  1322. {
  1323. hostView = ((Menu)view).Host;
  1324. }
  1325. View grabView = Application.MouseGrabView;
  1326. MenuBar hostGrabView = null;
  1327. if (grabView is MenuBar)
  1328. {
  1329. hostGrabView = (MenuBar)grabView;
  1330. }
  1331. else if (grabView is Menu)
  1332. {
  1333. hostGrabView = ((Menu)grabView).Host;
  1334. }
  1335. return hostView != hostGrabView ? hostGrabView : null;
  1336. }
  1337. #endregion Mouse Handling
  1338. /// <inheritdoc />
  1339. public bool EnableForDesign<TContext> (ref readonly TContext context) where TContext : notnull
  1340. {
  1341. if (context is not Func<string, bool> actionFn)
  1342. {
  1343. actionFn = (s) => true;
  1344. }
  1345. Menus =
  1346. [
  1347. new MenuBarItem (
  1348. "_File",
  1349. new MenuItem []
  1350. {
  1351. new (
  1352. "_New",
  1353. "",
  1354. () => actionFn ("New"),
  1355. null,
  1356. null,
  1357. KeyCode.CtrlMask | KeyCode.N
  1358. ),
  1359. new (
  1360. "_Open",
  1361. "",
  1362. () => actionFn ("Open"),
  1363. null,
  1364. null,
  1365. KeyCode.CtrlMask | KeyCode.O
  1366. ),
  1367. new (
  1368. "_Save",
  1369. "",
  1370. () => actionFn ("Save"),
  1371. null,
  1372. null,
  1373. KeyCode.CtrlMask | KeyCode.S
  1374. ),
  1375. null,
  1376. // Don't use Application.Quit so we can disambiguate between quitting and closing the toplevel
  1377. new (
  1378. "_Quit",
  1379. "",
  1380. () => actionFn ("Quit"),
  1381. null,
  1382. null,
  1383. KeyCode.CtrlMask | KeyCode.Q
  1384. )
  1385. }
  1386. ),
  1387. new MenuBarItem (
  1388. "_Edit",
  1389. new MenuItem []
  1390. {
  1391. new (
  1392. "_Copy",
  1393. "",
  1394. () => actionFn ("Copy"),
  1395. null,
  1396. null,
  1397. KeyCode.CtrlMask | KeyCode.C
  1398. ),
  1399. new (
  1400. "C_ut",
  1401. "",
  1402. () => actionFn ("Cut"),
  1403. null,
  1404. null,
  1405. KeyCode.CtrlMask | KeyCode.X
  1406. ),
  1407. new (
  1408. "_Paste",
  1409. "",
  1410. () => actionFn ("Paste"),
  1411. null,
  1412. null,
  1413. KeyCode.CtrlMask | KeyCode.V
  1414. ),
  1415. new MenuBarItem (
  1416. "_Find and Replace",
  1417. new MenuItem []
  1418. {
  1419. new (
  1420. "F_ind",
  1421. "",
  1422. () => actionFn ("Find"),
  1423. null,
  1424. null,
  1425. KeyCode.CtrlMask | KeyCode.F
  1426. ),
  1427. new (
  1428. "_Replace",
  1429. "",
  1430. () => actionFn ("Replace"),
  1431. null,
  1432. null,
  1433. KeyCode.CtrlMask | KeyCode.H
  1434. ),
  1435. new MenuBarItem (
  1436. "_3rd Level",
  1437. new MenuItem []
  1438. {
  1439. new (
  1440. "_1st",
  1441. "",
  1442. () => actionFn (
  1443. "1"
  1444. ),
  1445. null,
  1446. null,
  1447. KeyCode.F1
  1448. ),
  1449. new (
  1450. "_2nd",
  1451. "",
  1452. () => actionFn (
  1453. "2"
  1454. ),
  1455. null,
  1456. null,
  1457. KeyCode.F2
  1458. )
  1459. }
  1460. ),
  1461. new MenuBarItem (
  1462. "_4th Level",
  1463. new MenuItem []
  1464. {
  1465. new (
  1466. "_5th",
  1467. "",
  1468. () => actionFn (
  1469. "5"
  1470. ),
  1471. null,
  1472. null,
  1473. KeyCode.CtrlMask
  1474. | KeyCode.D5
  1475. ),
  1476. new (
  1477. "_6th",
  1478. "",
  1479. () => actionFn (
  1480. "6"
  1481. ),
  1482. null,
  1483. null,
  1484. KeyCode.CtrlMask
  1485. | KeyCode.D6
  1486. )
  1487. }
  1488. )
  1489. }
  1490. ),
  1491. new (
  1492. "_Select All",
  1493. "",
  1494. () => actionFn ("Select All"),
  1495. null,
  1496. null,
  1497. KeyCode.CtrlMask
  1498. | KeyCode.ShiftMask
  1499. | KeyCode.S
  1500. )
  1501. }
  1502. ),
  1503. new MenuBarItem ("_About", "Top-Level", () => actionFn ("About"))
  1504. ];
  1505. return true;
  1506. }
  1507. /// <inheritdoc />
  1508. protected override void Dispose (bool disposing)
  1509. {
  1510. MenuItem._menuBar = null;
  1511. base.Dispose (disposing);
  1512. }
  1513. }