MenuBar.cs 58 KB

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