MenuBar.cs 58 KB

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