MenuBar.cs 58 KB

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