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