Menu.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995
  1. using System;
  2. using NStack;
  3. using System.Linq;
  4. using System.Collections.Generic;
  5. namespace Terminal.Gui {
  6. /// <summary>
  7. /// Specifies how a <see cref="MenuItem"/> shows selection state.
  8. /// </summary>
  9. [Flags]
  10. public enum MenuItemCheckStyle {
  11. /// <summary>
  12. /// The menu item will be shown normally, with no check indicator. The default.
  13. /// </summary>
  14. NoCheck = 0b_0000_0000,
  15. /// <summary>
  16. /// The menu item will indicate checked/un-checked state (see <see cref="Checked"/>).
  17. /// </summary>
  18. Checked = 0b_0000_0001,
  19. /// <summary>
  20. /// The menu item is part of a menu radio group (see <see cref="Checked"/>) and will indicate selected state.
  21. /// </summary>
  22. Radio = 0b_0000_0010,
  23. };
  24. /// <summary>
  25. /// A <see cref="MenuItem"/> has title, an associated help text, and an action to execute on activation.
  26. /// MenuItems can also have a checked indicator (see <see cref="Checked"/>).
  27. /// </summary>
  28. public class MenuItem {
  29. ustring title;
  30. ShortcutHelper shortcutHelper;
  31. internal int TitleLength => GetMenuBarItemLength (Title);
  32. /// <summary>
  33. /// Gets or sets arbitrary data for the menu item.
  34. /// </summary>
  35. /// <remarks>This property is not used internally.</remarks>
  36. public object Data { get; set; }
  37. /// <summary>
  38. /// Initializes a new instance of <see cref="MenuItem"/>
  39. /// </summary>
  40. public MenuItem (Key shortcut = Key.Null) : this ("", "", null, null, null, shortcut) { }
  41. /// <summary>
  42. /// Initializes a new instance of <see cref="MenuItem"/>.
  43. /// </summary>
  44. /// <param name="title">Title for the menu item.</param>
  45. /// <param name="help">Help text to display.</param>
  46. /// <param name="action">Action to invoke when the menu item is activated.</param>
  47. /// <param name="canExecute">Function to determine if the action can currently be executed.</param>
  48. /// <param name="parent">The <see cref="Parent"/> of this menu item.</param>
  49. /// <param name="shortcut">The <see cref="Shortcut"/> keystroke combination.</param>
  50. public MenuItem (ustring title, ustring help, Action action, Func<bool> canExecute = null, MenuItem parent = null, Key shortcut = Key.Null)
  51. {
  52. Title = title ?? "";
  53. Help = help ?? "";
  54. Action = action;
  55. CanExecute = canExecute;
  56. Parent = parent;
  57. shortcutHelper = new ShortcutHelper ();
  58. if (shortcut != Key.Null) {
  59. shortcutHelper.Shortcut = shortcut;
  60. }
  61. }
  62. /// <summary>
  63. /// The HotKey is used to activate a <see cref="MenuItem"/> with the keyboard. HotKeys are defined by prefixing the <see cref="Title"/>
  64. /// of a MenuItem with an underscore ('_').
  65. /// <para>
  66. /// Pressing Alt-Hotkey for a <see cref="MenuBarItem"/> (menu items on the menu bar) works even if the menu is not active).
  67. /// Once a menu has focus and is active, pressing just the HotKey will activate the MenuItem.
  68. /// </para>
  69. /// <para>
  70. /// For example for a MenuBar with a "_File" MenuBarItem that contains a "_New" MenuItem, Alt-F will open the File menu.
  71. /// Pressing the N key will then activate the New MenuItem.
  72. /// </para>
  73. /// <para>
  74. /// See also <see cref="Shortcut"/> which enable global key-bindings to menu items.
  75. /// </para>
  76. /// </summary>
  77. public Rune HotKey;
  78. /// <summary>
  79. /// Shortcut defines a key binding to the MenuItem that will invoke the MenuItem's action globally for the <see cref="View"/> that is
  80. /// the parent of the <see cref="MenuBar"/> or <see cref="ContextMenu"/> this <see cref="MenuItem"/>.
  81. /// <para>
  82. /// The <see cref="Key"/> will be drawn on the MenuItem to the right of the <see cref="Title"/> and <see cref="Help"/> text. See <see cref="ShortcutTag"/>.
  83. /// </para>
  84. /// </summary>
  85. public Key Shortcut {
  86. get => shortcutHelper.Shortcut;
  87. set {
  88. if (shortcutHelper.Shortcut != value && (ShortcutHelper.PostShortcutValidation (value) || value == Key.Null)) {
  89. shortcutHelper.Shortcut = value;
  90. }
  91. }
  92. }
  93. /// <summary>
  94. /// Gets the text describing the keystroke combination defined by <see cref="Shortcut"/>.
  95. /// </summary>
  96. public ustring ShortcutTag => ShortcutHelper.GetShortcutTag (shortcutHelper.Shortcut);
  97. /// <summary>
  98. /// Gets or sets the title of the menu item .
  99. /// </summary>
  100. /// <value>The title.</value>
  101. public ustring Title {
  102. get { return title; }
  103. set {
  104. if (title != value) {
  105. title = value;
  106. GetHotKey ();
  107. }
  108. }
  109. }
  110. /// <summary>
  111. /// Gets or sets the help text for the menu item. The help text is drawn to the right of the <see cref="Title"/>.
  112. /// </summary>
  113. /// <value>The help text.</value>
  114. public ustring Help { get; set; }
  115. /// <summary>
  116. /// Gets or sets the action to be invoked when the menu item is triggered.
  117. /// </summary>
  118. /// <value>Method to invoke.</value>
  119. public Action Action { get; set; }
  120. /// <summary>
  121. /// Gets or sets the action to be invoked to determine if the menu can be triggered. If <see cref="CanExecute"/> returns <see langword="true"/>
  122. /// the menu item will be enabled. Otherwise, it will be disabled.
  123. /// </summary>
  124. /// <value>Function to determine if the action is can be executed or not.</value>
  125. public Func<bool> CanExecute { get; set; }
  126. /// <summary>
  127. /// Returns <see langword="true"/> if the menu item is enabled. This method is a wrapper around <see cref="CanExecute"/>.
  128. /// </summary>
  129. public bool IsEnabled ()
  130. {
  131. return CanExecute == null ? true : CanExecute ();
  132. }
  133. //
  134. // ┌─────────────────────────────┐
  135. // │ Quit Quit UI Catalog Ctrl+Q │
  136. // └─────────────────────────────┘
  137. // ┌─────────────────┐
  138. // │ ◌ TopLevel Alt+T │
  139. // └─────────────────┘
  140. // TODO: Replace the `2` literals with named constants
  141. internal int Width => 1 + // space before Title
  142. TitleLength +
  143. 2 + // space after Title - BUGBUG: This should be 1
  144. (Checked || CheckType.HasFlag (MenuItemCheckStyle.Checked) || CheckType.HasFlag (MenuItemCheckStyle.Radio) ? 2 : 0) + // check glyph + space
  145. (Help.ConsoleWidth > 0 ? 2 + Help.ConsoleWidth : 0) + // Two spaces before Help
  146. (ShortcutTag.ConsoleWidth > 0 ? 2 + ShortcutTag.ConsoleWidth : 0); // Pad two spaces before shortcut tag (which are also aligned right)
  147. /// <summary>
  148. /// Sets or gets whether the <see cref="MenuItem"/> shows a check indicator or not. See <see cref="MenuItemCheckStyle"/>.
  149. /// </summary>
  150. public bool Checked { set; get; }
  151. /// <summary>
  152. /// Sets or gets the <see cref="MenuItemCheckStyle"/> of a menu item where <see cref="Checked"/> is set to <see langword="true"/>.
  153. /// </summary>
  154. public MenuItemCheckStyle CheckType { get; set; }
  155. /// <summary>
  156. /// Gets the parent for this <see cref="MenuItem"/>.
  157. /// </summary>
  158. /// <value>The parent.</value>
  159. public MenuItem Parent { get; internal set; }
  160. /// <summary>
  161. /// Gets if this <see cref="MenuItem"/> is from a sub-menu.
  162. /// </summary>
  163. internal bool IsFromSubMenu { get { return Parent != null; } }
  164. /// <summary>
  165. /// Merely a debugging aid to see the interaction with main.
  166. /// </summary>
  167. public MenuItem GetMenuItem ()
  168. {
  169. return this;
  170. }
  171. /// <summary>
  172. /// Merely a debugging aid to see the interaction with main.
  173. /// </summary>
  174. public bool GetMenuBarItem ()
  175. {
  176. return IsFromSubMenu;
  177. }
  178. void GetHotKey ()
  179. {
  180. bool nextIsHot = false;
  181. foreach (var x in title) {
  182. if (x == MenuBar.HotKeySpecifier) {
  183. nextIsHot = true;
  184. } else {
  185. if (nextIsHot) {
  186. HotKey = Char.ToUpper ((char)x);
  187. break;
  188. }
  189. nextIsHot = false;
  190. HotKey = default;
  191. }
  192. }
  193. }
  194. int GetMenuBarItemLength (ustring title)
  195. {
  196. int len = 0;
  197. foreach (var ch in title) {
  198. if (ch == MenuBar.HotKeySpecifier)
  199. continue;
  200. len += Math.Max (Rune.ColumnWidth (ch), 1);
  201. }
  202. return len;
  203. }
  204. }
  205. /// <summary>
  206. /// <see cref="MenuBarItem"/> is a menu item on an app's <see cref="MenuBar"/>.
  207. /// MenuBarItems do not support <see cref="MenuItem.Shortcut"/>.
  208. /// </summary>
  209. public class MenuBarItem : MenuItem {
  210. /// <summary>
  211. /// Initializes a new <see cref="MenuBarItem"/> as a <see cref="MenuItem"/>.
  212. /// </summary>
  213. /// <param name="title">Title for the menu item.</param>
  214. /// <param name="help">Help text to display. Will be displayed next to the Title surrounded by parentheses.</param>
  215. /// <param name="action">Action to invoke when the menu item is activated.</param>
  216. /// <param name="canExecute">Function to determine if the action can currently be executed.</param>
  217. /// <param name="parent">The parent <see cref="MenuItem"/> of this if exist, otherwise is null.</param>
  218. public MenuBarItem (ustring title, ustring help, Action action, Func<bool> canExecute = null, MenuItem parent = null) : base (title, help, action, canExecute, parent)
  219. {
  220. Initialize (title, null, null, true);
  221. }
  222. /// <summary>
  223. /// Initializes a new <see cref="MenuBarItem"/>.
  224. /// </summary>
  225. /// <param name="title">Title for the menu item.</param>
  226. /// <param name="children">The items in the current menu.</param>
  227. /// <param name="parent">The parent <see cref="MenuItem"/> of this if exist, otherwise is null.</param>
  228. public MenuBarItem (ustring title, MenuItem [] children, MenuItem parent = null)
  229. {
  230. Initialize (title, children, parent);
  231. }
  232. /// <summary>
  233. /// Initializes a new <see cref="MenuBarItem"/> with separate list of items.
  234. /// </summary>
  235. /// <param name="title">Title for the menu item.</param>
  236. /// <param name="children">The list of items in the current menu.</param>
  237. /// <param name="parent">The parent <see cref="MenuItem"/> of this if exist, otherwise is null.</param>
  238. public MenuBarItem (ustring title, List<MenuItem []> children, MenuItem parent = null)
  239. {
  240. Initialize (title, children, parent);
  241. }
  242. /// <summary>
  243. /// Initializes a new <see cref="MenuBarItem"/>.
  244. /// </summary>
  245. /// <param name="children">The items in the current menu.</param>
  246. public MenuBarItem (MenuItem [] children) : this ("", children) { }
  247. /// <summary>
  248. /// Initializes a new <see cref="MenuBarItem"/>.
  249. /// </summary>
  250. public MenuBarItem () : this (children: new MenuItem [] { }) { }
  251. void Initialize (ustring title, object children, MenuItem parent = null, bool isTopLevel = false)
  252. {
  253. if (!isTopLevel && children == null) {
  254. throw new ArgumentNullException (nameof (children), "The parameter cannot be null. Use an empty array instead.");
  255. }
  256. SetTitle (title ?? "");
  257. if (parent != null) {
  258. Parent = parent;
  259. }
  260. if (children is List<MenuItem []>) {
  261. MenuItem [] childrens = new MenuItem [] { };
  262. foreach (var item in (List<MenuItem []>)children) {
  263. for (int i = 0; i < item.Length; i++) {
  264. SetChildrensParent (item);
  265. Array.Resize (ref childrens, childrens.Length + 1);
  266. childrens [childrens.Length - 1] = item [i];
  267. }
  268. }
  269. Children = childrens;
  270. } else if (children is MenuItem []) {
  271. SetChildrensParent ((MenuItem [])children);
  272. Children = (MenuItem [])children;
  273. } else {
  274. Children = null;
  275. }
  276. }
  277. void SetChildrensParent (MenuItem [] childrens)
  278. {
  279. foreach (var child in childrens) {
  280. if (child != null && child.Parent == null) {
  281. child.Parent = this;
  282. }
  283. }
  284. }
  285. /// <summary>
  286. /// Check if the children parameter is a <see cref="MenuBarItem"/>.
  287. /// </summary>
  288. /// <param name="children"></param>
  289. /// <returns>Returns a <see cref="MenuBarItem"/> or null otherwise.</returns>
  290. public MenuBarItem SubMenu (MenuItem children)
  291. {
  292. return children as MenuBarItem;
  293. }
  294. /// <summary>
  295. /// Check if the <see cref="MenuItem"/> parameter is a child of this.
  296. /// </summary>
  297. /// <param name="menuItem"></param>
  298. /// <returns>Returns <c>true</c> if it is a child of this. <c>false</c> otherwise.</returns>
  299. public bool IsSubMenuOf (MenuItem menuItem)
  300. {
  301. foreach (var child in Children) {
  302. if (child == menuItem && child.Parent == menuItem.Parent) {
  303. return true;
  304. }
  305. }
  306. return false;
  307. }
  308. /// <summary>
  309. /// Get the index of the <see cref="MenuItem"/> parameter.
  310. /// </summary>
  311. /// <param name="children"></param>
  312. /// <returns>Returns a value bigger than -1 if the <see cref="MenuItem"/> is a child of this.</returns>
  313. public int GetChildrenIndex (MenuItem children)
  314. {
  315. if (Children?.Length == 0) {
  316. return -1;
  317. }
  318. int i = 0;
  319. foreach (var child in Children) {
  320. if (child == children) {
  321. return i;
  322. }
  323. i++;
  324. }
  325. return -1;
  326. }
  327. void SetTitle (ustring title)
  328. {
  329. if (title == null)
  330. title = ustring.Empty;
  331. Title = title;
  332. }
  333. /// <summary>
  334. /// Gets or sets an array of <see cref="MenuItem"/> objects that are the children of this <see cref="MenuBarItem"/>
  335. /// </summary>
  336. /// <value>The children.</value>
  337. public MenuItem [] Children { get; set; }
  338. internal bool IsTopLevel { get => Parent == null && (Children == null || Children.Length == 0) && Action != null; }
  339. }
  340. class Menu : View {
  341. internal MenuBarItem barItems;
  342. internal MenuBar host;
  343. internal int current;
  344. internal View previousSubFocused;
  345. internal static Rect MakeFrame (int x, int y, MenuItem [] items, Menu parent = null)
  346. {
  347. if (items == null || items.Length == 0) {
  348. return new Rect ();
  349. }
  350. int minX = x;
  351. int minY = y;
  352. int maxW = (items.Max (z => z?.Width) ?? 0) + 2; // This 2 is frame border?
  353. int maxH = items.Length + 2; // This 2 is frame border?
  354. if (parent != null && x + maxW > Driver.Cols) {
  355. minX = Math.Max (parent.Frame.Right - parent.Frame.Width - maxW, 0);
  356. }
  357. if (y + maxH > Driver.Rows) {
  358. minY = Math.Max (Driver.Rows - maxH, 0);
  359. }
  360. return new Rect (minX, minY, maxW, maxH);
  361. }
  362. public Menu (MenuBar host, int x, int y, MenuBarItem barItems, Menu parent = null)
  363. : base (MakeFrame (x, y, barItems.Children, parent))
  364. {
  365. this.barItems = barItems;
  366. this.host = host;
  367. if (barItems.IsTopLevel) {
  368. // This is a standalone MenuItem on a MenuBar
  369. ColorScheme = host.ColorScheme;
  370. CanFocus = true;
  371. } else {
  372. current = -1;
  373. for (int i = 0; i < barItems.Children?.Length; i++) {
  374. if (barItems.Children [i] != null) {
  375. current = i;
  376. break;
  377. }
  378. }
  379. ColorScheme = host.ColorScheme;
  380. CanFocus = true;
  381. WantMousePositionReports = host.WantMousePositionReports;
  382. }
  383. // Things this view knows how to do
  384. AddCommand (Command.LineUp, () => MoveUp ());
  385. AddCommand (Command.LineDown, () => MoveDown ());
  386. AddCommand (Command.Left, () => { this.host.PreviousMenu (true); return true; });
  387. AddCommand (Command.Right, () => {
  388. this.host.NextMenu (!this.barItems.IsTopLevel || (this.barItems.Children != null
  389. && this.barItems.Children.Length > 0 && current > -1
  390. && current < this.barItems.Children.Length && this.barItems.Children [current].IsFromSubMenu),
  391. this.barItems.Children != null && this.barItems.Children.Length > 0 && current > -1
  392. && host.UseSubMenusSingleFrame && this.barItems.SubMenu (this.barItems.Children [current]) != null);
  393. return true;
  394. });
  395. AddCommand (Command.Cancel, () => { CloseAllMenus (); return true; });
  396. AddCommand (Command.Accept, () => { RunSelected (); return true; });
  397. // Default keybindings for this view
  398. AddKeyBinding (Key.CursorUp, Command.LineUp);
  399. AddKeyBinding (Key.CursorDown, Command.LineDown);
  400. AddKeyBinding (Key.CursorLeft, Command.Left);
  401. AddKeyBinding (Key.CursorRight, Command.Right);
  402. AddKeyBinding (Key.Esc, Command.Cancel);
  403. AddKeyBinding (Key.Enter, Command.Accept);
  404. }
  405. internal Attribute DetermineColorSchemeFor (MenuItem item, int index)
  406. {
  407. if (item != null) {
  408. if (index == current) return ColorScheme.Focus;
  409. if (!item.IsEnabled ()) return ColorScheme.Disabled;
  410. }
  411. return GetNormalColor ();
  412. }
  413. // Draws the Menu, within the Frame
  414. public override void Redraw (Rect bounds)
  415. {
  416. Driver.SetAttribute (GetNormalColor ());
  417. DrawFrame (Bounds, padding: 0, fill: true);
  418. for (int i = Bounds.Y; i < barItems.Children.Length; i++) {
  419. if (i < 0)
  420. continue;
  421. var item = barItems.Children [i];
  422. Driver.SetAttribute (item == null ? GetNormalColor ()
  423. : i == current ? ColorScheme.Focus : GetNormalColor ());
  424. if (item == null) {
  425. Move (0, i + 1);
  426. Driver.AddRune (Driver.LeftTee);
  427. } else if (Frame.X + 1 < Driver.Cols)
  428. Move (1, i + 1);
  429. Driver.SetAttribute (DetermineColorSchemeFor (item, i));
  430. for (int p = Bounds.X; p < Frame.Width - 2; p++) { // This - 2 is for the border
  431. if (p < 0)
  432. continue;
  433. if (item == null)
  434. Driver.AddRune (Driver.HLine);
  435. else if (i == 0 && p == 0 && host.UseSubMenusSingleFrame && item.Parent.Parent != null)
  436. Driver.AddRune (Driver.LeftArrow);
  437. // This `- 3` is left border + right border + one row in from right
  438. else if (p == Frame.Width - 3 && barItems.SubMenu (barItems.Children [i]) != null)
  439. Driver.AddRune (Driver.RightArrow);
  440. else
  441. Driver.AddRune (' ');
  442. }
  443. if (item == null) {
  444. if (SuperView?.Frame.Right - Frame.X > Frame.Width - 1) {
  445. Move (Frame.Width - 1, i + 1);
  446. Driver.AddRune (Driver.RightTee);
  447. }
  448. continue;
  449. }
  450. ustring textToDraw;
  451. var checkChar = Driver.Selected;
  452. var uncheckedChar = Driver.UnSelected;
  453. if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked)) {
  454. checkChar = Driver.Checked;
  455. uncheckedChar = Driver.UnChecked;
  456. }
  457. // Support Checked even though CheckType wasn't set
  458. if (item.Checked) {
  459. textToDraw = ustring.Make (new Rune [] { checkChar, ' ' }) + item.Title;
  460. } else if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked) || item.CheckType.HasFlag (MenuItemCheckStyle.Radio)) {
  461. textToDraw = ustring.Make (new Rune [] { uncheckedChar, ' ' }) + item.Title;
  462. } else {
  463. textToDraw = item.Title;
  464. }
  465. ViewToScreen (2, i + 1, out int vtsCol, out _, false);
  466. if (vtsCol < Driver.Cols) {
  467. Move (2, i + 1);
  468. if (!item.IsEnabled ()) {
  469. DrawHotString (textToDraw, ColorScheme.Disabled, ColorScheme.Disabled);
  470. } else if (i == 0 && host.UseSubMenusSingleFrame && item.Parent.Parent != null) {
  471. var tf = new TextFormatter () {
  472. Alignment = TextAlignment.Centered,
  473. HotKeySpecifier = MenuBar.HotKeySpecifier,
  474. Text = textToDraw
  475. };
  476. // The -3 is left/right border + one space (not sure what for)
  477. tf.Draw (ViewToScreen (new Rect (2, i + 1, Frame.Width - 3, 1)),
  478. i == current ? ColorScheme.Focus : GetNormalColor (),
  479. i == current ? ColorScheme.HotFocus : ColorScheme.HotNormal,
  480. SuperView == null ? default : SuperView.ViewToScreen (SuperView.Bounds));
  481. } else {
  482. DrawHotString (textToDraw,
  483. i == current ? ColorScheme.HotFocus : ColorScheme.HotNormal,
  484. i == current ? ColorScheme.Focus : GetNormalColor ());
  485. }
  486. // The help string
  487. var l = item.ShortcutTag.ConsoleWidth == 0 ? item.Help.ConsoleWidth : item.Help.ConsoleWidth + item.ShortcutTag.ConsoleWidth + 2;
  488. var col = Frame.Width - l - 2;
  489. ViewToScreen (col, i + 1, out vtsCol, out _, false);
  490. if (vtsCol < Driver.Cols) {
  491. Move (col, 1 + i);
  492. Driver.AddStr (item.Help);
  493. // The shortcut tag string
  494. if (!item.ShortcutTag.IsEmpty) {
  495. l = item.ShortcutTag.ConsoleWidth;
  496. Move (Frame.Width - l - 2, 1 + i);
  497. Driver.AddStr (item.ShortcutTag);
  498. }
  499. }
  500. }
  501. }
  502. PositionCursor ();
  503. }
  504. public override void PositionCursor ()
  505. {
  506. if (host == null || host.IsMenuOpen)
  507. if (barItems.IsTopLevel) {
  508. host.PositionCursor ();
  509. } else
  510. Move (2, 1 + current);
  511. else
  512. host.PositionCursor ();
  513. }
  514. public void Run (Action action)
  515. {
  516. if (action == null)
  517. return;
  518. Application.UngrabMouse ();
  519. host.CloseAllMenus ();
  520. Application.Refresh ();
  521. Application.MainLoop.AddIdle (() => {
  522. action ();
  523. return false;
  524. });
  525. }
  526. public override bool OnLeave (View view)
  527. {
  528. return host.OnLeave (view);
  529. }
  530. public override bool OnKeyDown (KeyEvent keyEvent)
  531. {
  532. if (keyEvent.IsAlt) {
  533. host.CloseAllMenus ();
  534. return true;
  535. }
  536. return false;
  537. }
  538. public override bool ProcessHotKey (KeyEvent keyEvent)
  539. {
  540. // To ncurses simulate a AltMask key pressing Alt+Space because
  541. // it can�t detect an alone special key down was pressed.
  542. if (keyEvent.IsAlt && keyEvent.Key == Key.AltMask) {
  543. OnKeyDown (keyEvent);
  544. return true;
  545. }
  546. return false;
  547. }
  548. public override bool ProcessKey (KeyEvent kb)
  549. {
  550. var result = InvokeKeybindings (kb);
  551. if (result != null)
  552. return (bool)result;
  553. // TODO: rune-ify
  554. if (barItems.Children != null && Char.IsLetterOrDigit ((char)kb.KeyValue)) {
  555. var x = Char.ToUpper ((char)kb.KeyValue);
  556. var idx = -1;
  557. foreach (var item in barItems.Children) {
  558. idx++;
  559. if (item == null) continue;
  560. if (item.IsEnabled () && item.HotKey == x) {
  561. current = idx;
  562. RunSelected ();
  563. return true;
  564. }
  565. }
  566. }
  567. return false;
  568. }
  569. void RunSelected ()
  570. {
  571. if (barItems.IsTopLevel) {
  572. Run (barItems.Action);
  573. } else if (current > -1 && barItems.Children [current].Action != null) {
  574. Run (barItems.Children [current].Action);
  575. } else if (current == 0 && host.UseSubMenusSingleFrame
  576. && barItems.Children [current].Parent.Parent != null) {
  577. host.PreviousMenu (barItems.Children [current].Parent.IsFromSubMenu, true);
  578. } else if (current > -1 && barItems.SubMenu (barItems.Children [current]) != null) {
  579. CheckSubMenu ();
  580. }
  581. }
  582. void CloseAllMenus ()
  583. {
  584. Application.UngrabMouse ();
  585. host.CloseAllMenus ();
  586. }
  587. bool MoveDown ()
  588. {
  589. if (barItems.IsTopLevel) {
  590. return true;
  591. }
  592. bool disabled;
  593. do {
  594. current++;
  595. if (current >= barItems.Children.Length) {
  596. current = 0;
  597. }
  598. if (this != host.openCurrentMenu && barItems.Children [current]?.IsFromSubMenu == true && host.selectedSub > -1) {
  599. host.PreviousMenu (true);
  600. host.SelectEnabledItem (barItems.Children, current, out current);
  601. host.openCurrentMenu = this;
  602. }
  603. var item = barItems.Children [current];
  604. if (item?.IsEnabled () != true) {
  605. disabled = true;
  606. } else {
  607. disabled = false;
  608. }
  609. if (!host.UseSubMenusSingleFrame && host.UseKeysUpDownAsKeysLeftRight && barItems.SubMenu (barItems.Children [current]) != null &&
  610. !disabled && host.IsMenuOpen) {
  611. if (!CheckSubMenu ())
  612. return false;
  613. break;
  614. }
  615. if (!host.IsMenuOpen) {
  616. host.OpenMenu (host.selected);
  617. }
  618. } while (barItems.Children [current] == null || disabled);
  619. SetNeedsDisplay ();
  620. if (!host.UseSubMenusSingleFrame)
  621. host.OnMenuOpened ();
  622. return true;
  623. }
  624. bool MoveUp ()
  625. {
  626. if (barItems.IsTopLevel || current == -1) {
  627. return true;
  628. }
  629. bool disabled;
  630. do {
  631. current--;
  632. if (host.UseKeysUpDownAsKeysLeftRight && !host.UseSubMenusSingleFrame) {
  633. if ((current == -1 || this != host.openCurrentMenu) && barItems.Children [current + 1].IsFromSubMenu && host.selectedSub > -1) {
  634. current++;
  635. host.PreviousMenu (true);
  636. if (current > 0) {
  637. current--;
  638. host.openCurrentMenu = this;
  639. }
  640. break;
  641. }
  642. }
  643. if (current < 0)
  644. current = barItems.Children.Length - 1;
  645. if (!host.SelectEnabledItem (barItems.Children, current, out current, false)) {
  646. current = 0;
  647. if (!host.SelectEnabledItem (barItems.Children, current, out current) && !host.CloseMenu (false)) {
  648. return false;
  649. }
  650. break;
  651. }
  652. var item = barItems.Children [current];
  653. if (item?.IsEnabled () != true) {
  654. disabled = true;
  655. } else {
  656. disabled = false;
  657. }
  658. if (!host.UseSubMenusSingleFrame && host.UseKeysUpDownAsKeysLeftRight && barItems.SubMenu (barItems.Children [current]) != null &&
  659. !disabled && host.IsMenuOpen) {
  660. if (!CheckSubMenu ())
  661. return false;
  662. break;
  663. }
  664. } while (barItems.Children [current] == null || disabled);
  665. SetNeedsDisplay ();
  666. if (!host.UseSubMenusSingleFrame)
  667. host.OnMenuOpened ();
  668. return true;
  669. }
  670. public override bool MouseEvent (MouseEvent me)
  671. {
  672. if (!host.handled && !host.HandleGrabView (me, this)) {
  673. return false;
  674. }
  675. host.handled = false;
  676. bool disabled;
  677. if (me.Flags == MouseFlags.Button1Clicked) {
  678. disabled = false;
  679. if (me.Y < 1)
  680. return true;
  681. var meY = me.Y - 1;
  682. if (meY >= barItems.Children.Length)
  683. return true;
  684. var item = barItems.Children [meY];
  685. if (item == null || !item.IsEnabled ()) disabled = true;
  686. current = meY;
  687. if (item != null && !disabled)
  688. RunSelected ();
  689. return true;
  690. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked ||
  691. me.Flags == MouseFlags.Button1TripleClicked || me.Flags == MouseFlags.ReportMousePosition ||
  692. me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  693. disabled = false;
  694. if (me.Y < 1 || me.Y - 1 >= barItems.Children.Length) {
  695. return true;
  696. }
  697. var item = barItems.Children [me.Y - 1];
  698. if (item == null) return true;
  699. if (item == null || !item.IsEnabled ()) disabled = true;
  700. if (item != null && !disabled)
  701. current = me.Y - 1;
  702. if (host.UseSubMenusSingleFrame || !CheckSubMenu ()) {
  703. SetNeedsDisplay ();
  704. return true;
  705. }
  706. host.OnMenuOpened ();
  707. return true;
  708. }
  709. return false;
  710. }
  711. internal bool CheckSubMenu ()
  712. {
  713. if (current == -1 || barItems.Children [current] == null) {
  714. return true;
  715. }
  716. var subMenu = barItems.SubMenu (barItems.Children [current]);
  717. if (subMenu != null) {
  718. int pos = -1;
  719. if (host.openSubMenu != null) {
  720. pos = host.openSubMenu.FindIndex (o => o?.barItems == subMenu);
  721. }
  722. if (pos == -1 && this != host.openCurrentMenu && subMenu.Children != host.openCurrentMenu.barItems.Children
  723. && !host.CloseMenu (false, true)) {
  724. return false;
  725. }
  726. host.Activate (host.selected, pos, subMenu);
  727. } else if (host.openSubMenu?.Count == 0 || host.openSubMenu?.Last ().barItems.IsSubMenuOf (barItems.Children [current]) == false) {
  728. return host.CloseMenu (false, true);
  729. } else {
  730. SetNeedsDisplay ();
  731. }
  732. return true;
  733. }
  734. int GetSubMenuIndex (MenuBarItem subMenu)
  735. {
  736. int pos = -1;
  737. if (this != null && Subviews.Count > 0) {
  738. Menu v = null;
  739. foreach (var menu in Subviews) {
  740. if (((Menu)menu).barItems == subMenu)
  741. v = (Menu)menu;
  742. }
  743. if (v != null)
  744. pos = Subviews.IndexOf (v);
  745. }
  746. return pos;
  747. }
  748. ///<inheritdoc/>
  749. public override bool OnEnter (View view)
  750. {
  751. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  752. return base.OnEnter (view);
  753. }
  754. }
  755. /// <summary>
  756. /// <para>
  757. /// Provides a menu bar that spans the top of a <see cref="Toplevel"/> View with drop-down and cascading menus.
  758. /// </para>
  759. /// <para>
  760. /// By default, any sub-sub-menus (sub-menus of the <see cref="MenuItem"/>s added to <see cref="MenuBarItem"/>s)
  761. /// are displayed in a cascading manner, where each sub-sub-menu pops out of the sub-menu frame
  762. /// (either to the right or left, depending on where the sub-menu is relative to the edge of the screen). By setting
  763. /// <see cref="UseSubMenusSingleFrame"/> to <see langword="true"/>, this behavior can be changed such that all sub-sub-menus are
  764. /// drawn within a single frame below the MenuBar.
  765. /// </para>
  766. /// </summary>
  767. /// <remarks>
  768. /// <para>
  769. /// The <see cref="MenuBar"/> appears on the first row of the parent <see cref="Toplevel"/> View and uses the full width.
  770. /// </para>
  771. /// <para>
  772. /// The <see cref="MenuBar"/> provides global hotkeys for the application. See <see cref="MenuItem.HotKey"/>.
  773. /// </para>
  774. /// <para>
  775. /// See also: <see cref="ContextMenu"/>
  776. /// </para>
  777. /// </remarks>
  778. public class MenuBar : View {
  779. internal int selected;
  780. internal int selectedSub;
  781. /// <summary>
  782. /// Gets or sets the array of <see cref="MenuBarItem"/>s for the menu. Only set this after the <see cref="MenuBar"/> is visible.
  783. /// </summary>
  784. /// <value>The menu array.</value>
  785. public MenuBarItem [] Menus { get; set; }
  786. private bool useKeysUpDownAsKeysLeftRight = false;
  787. /// <summary>
  788. /// Used for change the navigation key style.
  789. /// </summary>
  790. public bool UseKeysUpDownAsKeysLeftRight {
  791. get => useKeysUpDownAsKeysLeftRight;
  792. set {
  793. useKeysUpDownAsKeysLeftRight = value;
  794. if (value && UseSubMenusSingleFrame) {
  795. UseSubMenusSingleFrame = false;
  796. SetNeedsDisplay ();
  797. }
  798. }
  799. }
  800. static ustring shortcutDelimiter = "+";
  801. /// <summary>
  802. /// Sets or gets the shortcut delimiter separator. The default is "+".
  803. /// </summary>
  804. public static ustring ShortcutDelimiter {
  805. get => shortcutDelimiter;
  806. set {
  807. if (shortcutDelimiter != value) {
  808. shortcutDelimiter = value == ustring.Empty ? " " : value;
  809. }
  810. }
  811. }
  812. /// <summary>
  813. /// The specifier character for the hotkey to all menus.
  814. /// </summary>
  815. new public static Rune HotKeySpecifier => '_';
  816. private bool useSubMenusSingleFrame;
  817. /// <summary>
  818. /// Gets or sets if the sub-menus must be displayed in a single or multiple frames.
  819. /// <para>
  820. /// By default any sub-sub-menus (sub-menus of the main <see cref="MenuItem"/>s) are displayed in a cascading manner,
  821. /// where each sub-sub-menu pops out of the sub-menu frame
  822. /// (either to the right or left, depending on where the sub-menu is relative to the edge of the screen). By setting
  823. /// <see cref="UseSubMenusSingleFrame"/> to <see langword="true"/>, this behavior can be changed such that all sub-sub-menus are
  824. /// drawn within a single frame below the MenuBar.
  825. /// </para>
  826. /// </summary>
  827. public bool UseSubMenusSingleFrame {
  828. get => useSubMenusSingleFrame;
  829. set {
  830. useSubMenusSingleFrame = value;
  831. if (value && UseKeysUpDownAsKeysLeftRight) {
  832. useKeysUpDownAsKeysLeftRight = false;
  833. SetNeedsDisplay ();
  834. }
  835. }
  836. }
  837. /// <summary>
  838. /// Initializes a new instance of the <see cref="MenuBar"/>.
  839. /// </summary>
  840. public MenuBar () : this (new MenuBarItem [] { }) { }
  841. /// <summary>
  842. /// Initializes a new instance of the <see cref="MenuBar"/> class with the specified set of toplevel menu items.
  843. /// </summary>
  844. /// <param name="menus">Individual menu items; a null item will result in a separator being drawn.</param>
  845. public MenuBar (MenuBarItem [] menus) : base ()
  846. {
  847. X = 0;
  848. Y = 0;
  849. Width = Dim.Fill ();
  850. Height = 1;
  851. Menus = menus;
  852. //CanFocus = true;
  853. selected = -1;
  854. selectedSub = -1;
  855. ColorScheme = Colors.Menu;
  856. WantMousePositionReports = true;
  857. IsMenuOpen = false;
  858. // Things this view knows how to do
  859. AddCommand (Command.Left, () => { MoveLeft (); return true; });
  860. AddCommand (Command.Right, () => { MoveRight (); return true; });
  861. AddCommand (Command.Cancel, () => { CloseMenuBar (); return true; });
  862. AddCommand (Command.Accept, () => { ProcessMenu (selected, Menus [selected]); return true; });
  863. // Default keybindings for this view
  864. AddKeyBinding (Key.CursorLeft, Command.Left);
  865. AddKeyBinding (Key.CursorRight, Command.Right);
  866. AddKeyBinding (Key.Esc, Command.Cancel);
  867. AddKeyBinding (Key.C | Key.CtrlMask, Command.Cancel);
  868. AddKeyBinding (Key.CursorDown, Command.Accept);
  869. AddKeyBinding (Key.Enter, Command.Accept);
  870. }
  871. bool openedByAltKey;
  872. bool isCleaning;
  873. ///<inheritdoc/>
  874. public override bool OnLeave (View view)
  875. {
  876. if ((!(view is MenuBar) && !(view is Menu) || !(view is MenuBar) && !(view is Menu) && openMenu != null) && !isCleaning && !reopen) {
  877. CleanUp ();
  878. return true;
  879. }
  880. return false;
  881. }
  882. ///<inheritdoc/>
  883. public override bool OnKeyDown (KeyEvent keyEvent)
  884. {
  885. if (keyEvent.IsAlt || (keyEvent.IsCtrl && keyEvent.Key == (Key.CtrlMask | Key.Space))) {
  886. openedByAltKey = true;
  887. SetNeedsDisplay ();
  888. openedByHotKey = false;
  889. }
  890. return false;
  891. }
  892. ///<inheritdoc/>
  893. public override bool OnKeyUp (KeyEvent keyEvent)
  894. {
  895. if (keyEvent.IsAlt || keyEvent.Key == Key.AltMask || (keyEvent.IsCtrl && keyEvent.Key == (Key.CtrlMask | Key.Space))) {
  896. // User pressed Alt - this may be a precursor to a menu accelerator (e.g. Alt-F)
  897. if (openedByAltKey && !IsMenuOpen && openMenu == null && (((uint)keyEvent.Key & (uint)Key.CharMask) == 0
  898. || ((uint)keyEvent.Key & (uint)Key.CharMask) == (uint)Key.Space)) {
  899. // There's no open menu, the first menu item should be highlight.
  900. // The right way to do this is to SetFocus(MenuBar), but for some reason
  901. // that faults.
  902. var mbar = GetMouseGrabViewInstance (this);
  903. if (mbar != null) {
  904. mbar.CleanUp ();
  905. }
  906. //Activate (0);
  907. //StartMenu ();
  908. IsMenuOpen = true;
  909. selected = 0;
  910. CanFocus = true;
  911. lastFocused = SuperView == null ? Application.Current.MostFocused : SuperView.MostFocused;
  912. SetFocus ();
  913. SetNeedsDisplay ();
  914. Application.GrabMouse (this);
  915. } else if (!openedByHotKey) {
  916. // There's an open menu. If this Alt key-up is a pre-cursor to an accelerator
  917. // we don't want to close the menu because it'll flash.
  918. // How to deal with that?
  919. CleanUp ();
  920. }
  921. return true;
  922. }
  923. return false;
  924. }
  925. internal void CleanUp ()
  926. {
  927. isCleaning = true;
  928. if (openMenu != null) {
  929. CloseAllMenus ();
  930. }
  931. openedByAltKey = false;
  932. IsMenuOpen = false;
  933. selected = -1;
  934. CanFocus = false;
  935. if (lastFocused != null) {
  936. lastFocused.SetFocus ();
  937. }
  938. SetNeedsDisplay ();
  939. Application.UngrabMouse ();
  940. isCleaning = false;
  941. }
  942. // The column where the MenuBar starts
  943. static int xOrigin = 0;
  944. // Spaces before the Title
  945. static int leftPadding = 1;
  946. // Spaces after the Title
  947. static int rightPadding = 1;
  948. // Spaces after the submenu Title, before Help
  949. static int parensAroundHelp = 3;
  950. ///<inheritdoc/>
  951. public override void Redraw (Rect bounds)
  952. {
  953. Move (0, 0);
  954. Driver.SetAttribute (GetNormalColor ());
  955. for (int i = 0; i < Frame.Width; i++)
  956. Driver.AddRune (' ');
  957. Move (1, 0);
  958. int pos = 0;
  959. for (int i = 0; i < Menus.Length; i++) {
  960. var menu = Menus [i];
  961. Move (pos, 0);
  962. Attribute hotColor, normalColor;
  963. if (i == selected && IsMenuOpen) {
  964. hotColor = i == selected ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  965. normalColor = i == selected ? ColorScheme.Focus :
  966. GetNormalColor ();
  967. } else if (openedByAltKey) {
  968. hotColor = ColorScheme.HotNormal;
  969. normalColor = GetNormalColor ();
  970. } else {
  971. hotColor = GetNormalColor ();
  972. normalColor = GetNormalColor ();
  973. }
  974. // Note Help on MenuBar is drawn with parens around it
  975. DrawHotString (menu.Help.IsEmpty ? $" {menu.Title} " : $" {menu.Title} ({menu.Help}) ", hotColor, normalColor);
  976. pos += leftPadding + menu.TitleLength + (menu.Help.ConsoleWidth > 0 ? leftPadding + menu.Help.ConsoleWidth + parensAroundHelp : 0) + rightPadding;
  977. }
  978. PositionCursor ();
  979. }
  980. ///<inheritdoc/>
  981. public override void PositionCursor ()
  982. {
  983. if (selected == -1 && HasFocus && Menus.Length > 0) {
  984. selected = 0;
  985. }
  986. int pos = 0;
  987. for (int i = 0; i < Menus.Length; i++) {
  988. if (i == selected) {
  989. pos++;
  990. Move (pos + 1, 0);
  991. return;
  992. } else {
  993. pos += leftPadding + Menus [i].TitleLength + (Menus [i].Help.ConsoleWidth > 0 ? Menus [i].Help.ConsoleWidth + parensAroundHelp : 0) + rightPadding;
  994. }
  995. }
  996. }
  997. void Selected (MenuItem item)
  998. {
  999. var action = item.Action;
  1000. if (action == null)
  1001. return;
  1002. Application.UngrabMouse ();
  1003. CloseAllMenus ();
  1004. Application.Refresh ();
  1005. Application.MainLoop.AddIdle (() => {
  1006. action ();
  1007. return false;
  1008. });
  1009. }
  1010. /// <summary>
  1011. /// Raised as a menu is opening.
  1012. /// </summary>
  1013. public event Action<MenuOpeningEventArgs> MenuOpening;
  1014. /// <summary>
  1015. /// Raised when a menu is opened.
  1016. /// </summary>
  1017. public event Action<MenuItem> MenuOpened;
  1018. /// <summary>
  1019. /// Raised when a menu is closing passing <see cref="MenuClosingEventArgs"/>.
  1020. /// </summary>
  1021. public event Action<MenuClosingEventArgs> MenuClosing;
  1022. /// <summary>
  1023. /// Raised when all the menu is closed.
  1024. /// </summary>
  1025. public event Action MenuAllClosed;
  1026. internal Menu openMenu;
  1027. Menu ocm;
  1028. internal Menu openCurrentMenu {
  1029. get => ocm;
  1030. set {
  1031. if (ocm != value) {
  1032. ocm = value;
  1033. if (ocm.current > -1) {
  1034. OnMenuOpened ();
  1035. }
  1036. }
  1037. }
  1038. }
  1039. internal List<Menu> openSubMenu;
  1040. View previousFocused;
  1041. internal bool isMenuOpening;
  1042. internal bool isMenuClosing;
  1043. /// <summary>
  1044. /// <see langword="true"/> if the menu is open; otherwise <see langword="true"/>.
  1045. /// </summary>
  1046. public bool IsMenuOpen { get; protected set; }
  1047. /// <summary>
  1048. /// Virtual method that will invoke the <see cref="MenuOpening"/> event if it's defined.
  1049. /// </summary>
  1050. /// <param name="currentMenu">The current menu to be replaced.</param>
  1051. /// <returns>Returns the <see cref="MenuOpeningEventArgs"/></returns>
  1052. public virtual MenuOpeningEventArgs OnMenuOpening (MenuBarItem currentMenu)
  1053. {
  1054. var ev = new MenuOpeningEventArgs (currentMenu);
  1055. MenuOpening?.Invoke (ev);
  1056. return ev;
  1057. }
  1058. /// <summary>
  1059. /// Virtual method that will invoke the <see cref="MenuOpened"/> event if it's defined.
  1060. /// </summary>
  1061. public virtual void OnMenuOpened ()
  1062. {
  1063. MenuItem mi = null;
  1064. if (openCurrentMenu.barItems.Children != null && openCurrentMenu?.current > -1) {
  1065. mi = openCurrentMenu.barItems.Children [openCurrentMenu.current];
  1066. } else if (openCurrentMenu.barItems.IsTopLevel) {
  1067. mi = openCurrentMenu.barItems;
  1068. } else {
  1069. mi = openMenu.barItems.Children [openMenu.current];
  1070. }
  1071. MenuOpened?.Invoke (mi);
  1072. }
  1073. /// <summary>
  1074. /// Virtual method that will invoke the <see cref="MenuClosing"/>.
  1075. /// </summary>
  1076. /// <param name="currentMenu">The current menu to be closed.</param>
  1077. /// <param name="reopen">Whether the current menu will be reopen.</param>
  1078. /// <param name="isSubMenu">Whether is a sub-menu or not.</param>
  1079. public virtual MenuClosingEventArgs OnMenuClosing (MenuBarItem currentMenu, bool reopen, bool isSubMenu)
  1080. {
  1081. var ev = new MenuClosingEventArgs (currentMenu, reopen, isSubMenu);
  1082. MenuClosing?.Invoke (ev);
  1083. return ev;
  1084. }
  1085. /// <summary>
  1086. /// Virtual method that will invoke the <see cref="MenuAllClosed"/>.
  1087. /// </summary>
  1088. public virtual void OnMenuAllClosed ()
  1089. {
  1090. MenuAllClosed?.Invoke ();
  1091. }
  1092. View lastFocused;
  1093. /// <summary>
  1094. /// Gets the view that was last focused before opening the menu.
  1095. /// </summary>
  1096. public View LastFocused { get; private set; }
  1097. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem subMenu = null)
  1098. {
  1099. isMenuOpening = true;
  1100. var newMenu = OnMenuOpening (Menus [index]);
  1101. if (newMenu.Cancel) {
  1102. isMenuOpening = false;
  1103. return;
  1104. }
  1105. if (newMenu.NewMenuBarItem != null) {
  1106. Menus [index] = newMenu.NewMenuBarItem;
  1107. }
  1108. int pos = 0;
  1109. switch (subMenu) {
  1110. case null:
  1111. // Open a submenu below a MenuBar
  1112. lastFocused = lastFocused ?? (SuperView == null ? Application.Current.MostFocused : SuperView.MostFocused);
  1113. if (openSubMenu != null && !CloseMenu (false, true))
  1114. return;
  1115. if (openMenu != null) {
  1116. if (SuperView == null) {
  1117. Application.Current.Remove (openMenu);
  1118. } else {
  1119. SuperView.Remove (openMenu);
  1120. }
  1121. openMenu.Dispose ();
  1122. }
  1123. // This positions the submenu horizontally aligned with the first character of the
  1124. // menu it belongs to's text
  1125. for (int i = 0; i < index; i++)
  1126. pos += Menus [i].TitleLength + (Menus [i].Help.ConsoleWidth > 0 ? Menus [i].Help.ConsoleWidth + 2 : 0) + leftPadding + rightPadding;
  1127. openMenu = new Menu (this, Frame.X + pos, Frame.Y + 1, Menus [index]);
  1128. openCurrentMenu = openMenu;
  1129. openCurrentMenu.previousSubFocused = openMenu;
  1130. if (SuperView == null) {
  1131. Application.Current.Add (openMenu);
  1132. } else {
  1133. SuperView.Add (openMenu);
  1134. }
  1135. openMenu.SetFocus ();
  1136. break;
  1137. default:
  1138. // Opens a submenu next to another submenu (openSubMenu)
  1139. if (openSubMenu == null)
  1140. openSubMenu = new List<Menu> ();
  1141. if (sIndex > -1) {
  1142. RemoveSubMenu (sIndex);
  1143. } else {
  1144. var last = openSubMenu.Count > 0 ? openSubMenu.Last () : openMenu;
  1145. if (!UseSubMenusSingleFrame) {
  1146. openCurrentMenu = new Menu (this, last.Frame.Left + last.Frame.Width, last.Frame.Top + 1 + last.current, subMenu, last);
  1147. } else {
  1148. var first = openSubMenu.Count > 0 ? openSubMenu.First () : openMenu;
  1149. var mbi = new MenuItem [2 + subMenu.Children.Length];
  1150. mbi [0] = new MenuItem () { Title = subMenu.Title, Parent = subMenu };
  1151. mbi [1] = null;
  1152. for (int j = 0; j < subMenu.Children.Length; j++) {
  1153. mbi [j + 2] = subMenu.Children [j];
  1154. }
  1155. var newSubMenu = new MenuBarItem (mbi);
  1156. openCurrentMenu = new Menu (this, first.Frame.Left, first.Frame.Top, newSubMenu);
  1157. last.Visible = false;
  1158. Application.GrabMouse (openCurrentMenu);
  1159. }
  1160. openCurrentMenu.previousSubFocused = last.previousSubFocused;
  1161. openSubMenu.Add (openCurrentMenu);
  1162. if (SuperView == null) {
  1163. Application.Current.Add (openCurrentMenu);
  1164. } else {
  1165. SuperView.Add (openCurrentMenu);
  1166. }
  1167. }
  1168. selectedSub = openSubMenu.Count - 1;
  1169. if (selectedSub > -1 && SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  1170. openCurrentMenu.SetFocus ();
  1171. }
  1172. break;
  1173. }
  1174. isMenuOpening = false;
  1175. IsMenuOpen = true;
  1176. }
  1177. /// <summary>
  1178. /// Opens the Menu programatically, as though the F9 key were pressed.
  1179. /// </summary>
  1180. public void OpenMenu ()
  1181. {
  1182. var mbar = GetMouseGrabViewInstance (this);
  1183. if (mbar != null) {
  1184. mbar.CleanUp ();
  1185. }
  1186. if (openMenu != null)
  1187. return;
  1188. selected = 0;
  1189. SetNeedsDisplay ();
  1190. previousFocused = SuperView == null ? Application.Current.Focused : SuperView.Focused;
  1191. OpenMenu (selected);
  1192. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current) && !CloseMenu (false)) {
  1193. return;
  1194. }
  1195. if (!openCurrentMenu.CheckSubMenu ())
  1196. return;
  1197. Application.GrabMouse (this);
  1198. }
  1199. // Activates the menu, handles either first focus, or activating an entry when it was already active
  1200. // For mouse events.
  1201. internal void Activate (int idx, int sIdx = -1, MenuBarItem subMenu = null)
  1202. {
  1203. selected = idx;
  1204. selectedSub = sIdx;
  1205. if (openMenu == null)
  1206. previousFocused = SuperView == null ? Application.Current.Focused : SuperView.Focused;
  1207. OpenMenu (idx, sIdx, subMenu);
  1208. SetNeedsDisplay ();
  1209. }
  1210. internal bool SelectEnabledItem (IEnumerable<MenuItem> chldren, int current, out int newCurrent, bool forward = true)
  1211. {
  1212. if (chldren == null) {
  1213. newCurrent = -1;
  1214. return true;
  1215. }
  1216. IEnumerable<MenuItem> childrens;
  1217. if (forward) {
  1218. childrens = chldren;
  1219. } else {
  1220. childrens = chldren.Reverse ();
  1221. }
  1222. int count;
  1223. if (forward) {
  1224. count = -1;
  1225. } else {
  1226. count = childrens.Count ();
  1227. }
  1228. foreach (var child in childrens) {
  1229. if (forward) {
  1230. if (++count < current) {
  1231. continue;
  1232. }
  1233. } else {
  1234. if (--count > current) {
  1235. continue;
  1236. }
  1237. }
  1238. if (child == null || !child.IsEnabled ()) {
  1239. if (forward) {
  1240. current++;
  1241. } else {
  1242. current--;
  1243. }
  1244. } else {
  1245. newCurrent = current;
  1246. return true;
  1247. }
  1248. }
  1249. newCurrent = -1;
  1250. return false;
  1251. }
  1252. /// <summary>
  1253. /// Closes the Menu programmatically if open and not canceled (as though F9 were pressed).
  1254. /// </summary>
  1255. public bool CloseMenu (bool ignoreUseSubMenusSingleFrame = false)
  1256. {
  1257. return CloseMenu (false, false, ignoreUseSubMenusSingleFrame);
  1258. }
  1259. bool reopen;
  1260. internal bool CloseMenu (bool reopen = false, bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  1261. {
  1262. var mbi = isSubMenu ? openCurrentMenu.barItems : openMenu?.barItems;
  1263. if (UseSubMenusSingleFrame && mbi != null &&
  1264. !ignoreUseSubMenusSingleFrame && mbi.Parent != null) {
  1265. return false;
  1266. }
  1267. isMenuClosing = true;
  1268. this.reopen = reopen;
  1269. var args = OnMenuClosing (mbi, reopen, isSubMenu);
  1270. if (args.Cancel) {
  1271. isMenuClosing = false;
  1272. if (args.CurrentMenu.Parent != null)
  1273. openMenu.current = ((MenuBarItem)args.CurrentMenu.Parent).Children.IndexOf (args.CurrentMenu);
  1274. return false;
  1275. }
  1276. switch (isSubMenu) {
  1277. case false:
  1278. if (openMenu != null) {
  1279. if (SuperView == null) {
  1280. Application.Current.Remove (openMenu);
  1281. } else {
  1282. SuperView?.Remove (openMenu);
  1283. }
  1284. }
  1285. SetNeedsDisplay ();
  1286. if (previousFocused != null && previousFocused is Menu && openMenu != null && previousFocused.ToString () != openCurrentMenu.ToString ())
  1287. previousFocused.SetFocus ();
  1288. openMenu?.Dispose ();
  1289. openMenu = null;
  1290. if (lastFocused is Menu || lastFocused is MenuBar) {
  1291. lastFocused = null;
  1292. }
  1293. LastFocused = lastFocused;
  1294. lastFocused = null;
  1295. if (LastFocused != null && LastFocused.CanFocus) {
  1296. if (!reopen) {
  1297. selected = -1;
  1298. }
  1299. LastFocused.SetFocus ();
  1300. } else {
  1301. SetFocus ();
  1302. PositionCursor ();
  1303. }
  1304. IsMenuOpen = false;
  1305. break;
  1306. case true:
  1307. selectedSub = -1;
  1308. SetNeedsDisplay ();
  1309. RemoveAllOpensSubMenus ();
  1310. openCurrentMenu.previousSubFocused.SetFocus ();
  1311. openSubMenu = null;
  1312. IsMenuOpen = true;
  1313. break;
  1314. }
  1315. this.reopen = false;
  1316. isMenuClosing = false;
  1317. return true;
  1318. }
  1319. void RemoveSubMenu (int index, bool ignoreUseSubMenusSingleFrame = false)
  1320. {
  1321. if (openSubMenu == null || (UseSubMenusSingleFrame
  1322. && !ignoreUseSubMenusSingleFrame && openSubMenu.Count == 0))
  1323. return;
  1324. for (int i = openSubMenu.Count - 1; i > index; i--) {
  1325. isMenuClosing = true;
  1326. Menu menu;
  1327. if (openSubMenu.Count - 1 > 0)
  1328. menu = openSubMenu [i - 1];
  1329. else
  1330. menu = openMenu;
  1331. if (!menu.Visible)
  1332. menu.Visible = true;
  1333. openCurrentMenu = menu;
  1334. openCurrentMenu.SetFocus ();
  1335. if (openSubMenu != null) {
  1336. menu = openSubMenu [i];
  1337. if (SuperView == null) {
  1338. Application.Current.Remove (menu);
  1339. } else {
  1340. SuperView.Remove (menu);
  1341. }
  1342. openSubMenu.Remove (menu);
  1343. menu.Dispose ();
  1344. }
  1345. RemoveSubMenu (i, ignoreUseSubMenusSingleFrame);
  1346. }
  1347. if (openSubMenu.Count > 0)
  1348. openCurrentMenu = openSubMenu.Last ();
  1349. isMenuClosing = false;
  1350. }
  1351. internal void RemoveAllOpensSubMenus ()
  1352. {
  1353. if (openSubMenu != null) {
  1354. foreach (var item in openSubMenu) {
  1355. if (SuperView == null) {
  1356. Application.Current.Remove (item);
  1357. } else {
  1358. SuperView.Remove (item);
  1359. }
  1360. item.Dispose ();
  1361. }
  1362. }
  1363. }
  1364. internal void CloseAllMenus ()
  1365. {
  1366. if (!isMenuOpening && !isMenuClosing) {
  1367. if (openSubMenu != null && !CloseMenu (false, true))
  1368. return;
  1369. if (!CloseMenu (false))
  1370. return;
  1371. if (LastFocused != null && LastFocused != this)
  1372. selected = -1;
  1373. Application.UngrabMouse ();
  1374. }
  1375. IsMenuOpen = false;
  1376. openedByHotKey = false;
  1377. openedByAltKey = false;
  1378. OnMenuAllClosed ();
  1379. }
  1380. View FindDeepestMenu (View view, ref int count)
  1381. {
  1382. count = count > 0 ? count : 0;
  1383. foreach (var menu in view.Subviews) {
  1384. if (menu is Menu) {
  1385. count++;
  1386. return FindDeepestMenu ((Menu)menu, ref count);
  1387. }
  1388. }
  1389. return view;
  1390. }
  1391. internal void PreviousMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  1392. {
  1393. switch (isSubMenu) {
  1394. case false:
  1395. if (selected <= 0)
  1396. selected = Menus.Length - 1;
  1397. else
  1398. selected--;
  1399. if (selected > -1 && !CloseMenu (true, false, ignoreUseSubMenusSingleFrame))
  1400. return;
  1401. OpenMenu (selected);
  1402. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current, false)) {
  1403. openCurrentMenu.current = 0;
  1404. }
  1405. break;
  1406. case true:
  1407. if (selectedSub > -1) {
  1408. selectedSub--;
  1409. RemoveSubMenu (selectedSub, ignoreUseSubMenusSingleFrame);
  1410. SetNeedsDisplay ();
  1411. } else
  1412. PreviousMenu ();
  1413. break;
  1414. }
  1415. }
  1416. internal void NextMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  1417. {
  1418. switch (isSubMenu) {
  1419. case false:
  1420. if (selected == -1)
  1421. selected = 0;
  1422. else if (selected + 1 == Menus.Length)
  1423. selected = 0;
  1424. else
  1425. selected++;
  1426. if (selected > -1 && !CloseMenu (true, ignoreUseSubMenusSingleFrame))
  1427. return;
  1428. OpenMenu (selected);
  1429. SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current);
  1430. break;
  1431. case true:
  1432. if (UseKeysUpDownAsKeysLeftRight) {
  1433. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame)) {
  1434. NextMenu (false, ignoreUseSubMenusSingleFrame);
  1435. }
  1436. } else {
  1437. var subMenu = openCurrentMenu.current > -1 && openCurrentMenu.barItems.Children.Length > 0
  1438. ? openCurrentMenu.barItems.SubMenu (openCurrentMenu.barItems.Children [openCurrentMenu.current])
  1439. : null;
  1440. if ((selectedSub == -1 || openSubMenu == null || openSubMenu?.Count == selectedSub) && subMenu == null) {
  1441. if (openSubMenu != null && !CloseMenu (false, true))
  1442. return;
  1443. NextMenu (false, ignoreUseSubMenusSingleFrame);
  1444. } else if (subMenu != null || (openCurrentMenu.current > -1
  1445. && !openCurrentMenu.barItems.Children [openCurrentMenu.current].IsFromSubMenu)) {
  1446. selectedSub++;
  1447. openCurrentMenu.CheckSubMenu ();
  1448. } else {
  1449. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame)) {
  1450. NextMenu (false, ignoreUseSubMenusSingleFrame);
  1451. }
  1452. return;
  1453. }
  1454. SetNeedsDisplay ();
  1455. if (UseKeysUpDownAsKeysLeftRight)
  1456. openCurrentMenu.CheckSubMenu ();
  1457. }
  1458. break;
  1459. }
  1460. }
  1461. bool openedByHotKey;
  1462. internal bool FindAndOpenMenuByHotkey (KeyEvent kb)
  1463. {
  1464. //int pos = 0;
  1465. var c = ((uint)kb.Key & (uint)Key.CharMask);
  1466. for (int i = 0; i < Menus.Length; i++) {
  1467. // TODO: this code is duplicated, hotkey should be part of the MenuBarItem
  1468. var mi = Menus [i];
  1469. int p = mi.Title.IndexOf (MenuBar.HotKeySpecifier);
  1470. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1471. if (Char.ToUpperInvariant ((char)mi.Title [p + 1]) == c) {
  1472. ProcessMenu (i, mi);
  1473. return true;
  1474. }
  1475. }
  1476. }
  1477. return false;
  1478. }
  1479. internal bool FindAndOpenMenuByShortcut (KeyEvent kb, MenuItem [] children = null)
  1480. {
  1481. if (children == null) {
  1482. children = Menus;
  1483. }
  1484. var key = kb.KeyValue;
  1485. var keys = ShortcutHelper.GetModifiersKey (kb);
  1486. key |= (int)keys;
  1487. for (int i = 0; i < children.Length; i++) {
  1488. var mi = children [i];
  1489. if (mi == null) {
  1490. continue;
  1491. }
  1492. if ((!(mi is MenuBarItem mbiTopLevel) || mbiTopLevel.IsTopLevel) && mi.Shortcut != Key.Null && mi.Shortcut == (Key)key) {
  1493. var action = mi.Action;
  1494. if (action != null) {
  1495. Application.MainLoop.AddIdle (() => {
  1496. action ();
  1497. return false;
  1498. });
  1499. }
  1500. return true;
  1501. }
  1502. if (mi is MenuBarItem menuBarItem && !menuBarItem.IsTopLevel && FindAndOpenMenuByShortcut (kb, menuBarItem.Children)) {
  1503. return true;
  1504. }
  1505. }
  1506. return false;
  1507. }
  1508. private void ProcessMenu (int i, MenuBarItem mi)
  1509. {
  1510. if (selected < 0 && IsMenuOpen) {
  1511. return;
  1512. }
  1513. if (mi.IsTopLevel) {
  1514. var menu = new Menu (this, i, 0, mi);
  1515. menu.Run (mi.Action);
  1516. menu.Dispose ();
  1517. } else {
  1518. openedByHotKey = true;
  1519. Application.GrabMouse (this);
  1520. selected = i;
  1521. OpenMenu (i);
  1522. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current) && !CloseMenu (false)) {
  1523. return;
  1524. }
  1525. if (!openCurrentMenu.CheckSubMenu ())
  1526. return;
  1527. }
  1528. SetNeedsDisplay ();
  1529. }
  1530. ///<inheritdoc/>
  1531. public override bool ProcessHotKey (KeyEvent kb)
  1532. {
  1533. if (kb.Key == Key.F9) {
  1534. if (!IsMenuOpen)
  1535. OpenMenu ();
  1536. else
  1537. CloseAllMenus ();
  1538. return true;
  1539. }
  1540. // To ncurses simulate a AltMask key pressing Alt+Space because
  1541. // it can't detect an alone special key down was pressed.
  1542. if (kb.IsAlt && kb.Key == Key.AltMask && openMenu == null) {
  1543. OnKeyDown (kb);
  1544. OnKeyUp (kb);
  1545. return true;
  1546. } else if (kb.IsAlt && !kb.IsCtrl && !kb.IsShift) {
  1547. if (FindAndOpenMenuByHotkey (kb)) return true;
  1548. }
  1549. //var kc = kb.KeyValue;
  1550. return base.ProcessHotKey (kb);
  1551. }
  1552. ///<inheritdoc/>
  1553. public override bool ProcessKey (KeyEvent kb)
  1554. {
  1555. if (InvokeKeybindings (kb) == true)
  1556. return true;
  1557. var key = kb.KeyValue;
  1558. if ((key >= 'a' && key <= 'z') || (key >= 'A' && key <= 'Z') || (key >= '0' && key <= '9')) {
  1559. char c = Char.ToUpper ((char)key);
  1560. if (selected == -1 || Menus [selected].IsTopLevel)
  1561. return false;
  1562. foreach (var mi in Menus [selected].Children) {
  1563. if (mi == null)
  1564. continue;
  1565. int p = mi.Title.IndexOf (MenuBar.HotKeySpecifier);
  1566. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1567. if (mi.Title [p + 1] == c) {
  1568. Selected (mi);
  1569. return true;
  1570. }
  1571. }
  1572. }
  1573. }
  1574. return false;
  1575. }
  1576. void CloseMenuBar ()
  1577. {
  1578. if (!CloseMenu (false))
  1579. return;
  1580. if (openedByAltKey) {
  1581. openedByAltKey = false;
  1582. LastFocused?.SetFocus ();
  1583. }
  1584. SetNeedsDisplay ();
  1585. }
  1586. void MoveRight ()
  1587. {
  1588. selected = (selected + 1) % Menus.Length;
  1589. OpenMenu (selected);
  1590. SetNeedsDisplay ();
  1591. }
  1592. void MoveLeft ()
  1593. {
  1594. selected--;
  1595. if (selected < 0)
  1596. selected = Menus.Length - 1;
  1597. OpenMenu (selected);
  1598. SetNeedsDisplay ();
  1599. }
  1600. ///<inheritdoc/>
  1601. public override bool ProcessColdKey (KeyEvent kb)
  1602. {
  1603. return FindAndOpenMenuByShortcut (kb);
  1604. }
  1605. ///<inheritdoc/>
  1606. public override bool MouseEvent (MouseEvent me)
  1607. {
  1608. if (!handled && !HandleGrabView (me, this)) {
  1609. return false;
  1610. }
  1611. handled = false;
  1612. if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked || me.Flags == MouseFlags.Button1Clicked ||
  1613. (me.Flags == MouseFlags.ReportMousePosition && selected > -1) ||
  1614. (me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && selected > -1)) {
  1615. int pos = xOrigin;
  1616. int cx = me.X;
  1617. for (int i = 0; i < Menus.Length; i++) {
  1618. if (cx >= pos && cx < pos + leftPadding + Menus [i].TitleLength + Menus [i].Help.ConsoleWidth + rightPadding) {
  1619. if (me.Flags == MouseFlags.Button1Clicked) {
  1620. if (Menus [i].IsTopLevel) {
  1621. var menu = new Menu (this, i, 0, Menus [i]);
  1622. menu.Run (Menus [i].Action);
  1623. menu.Dispose ();
  1624. } else if (!IsMenuOpen) {
  1625. Activate (i);
  1626. }
  1627. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked) {
  1628. if (IsMenuOpen && !Menus [i].IsTopLevel) {
  1629. CloseAllMenus ();
  1630. } else if (!Menus [i].IsTopLevel) {
  1631. Activate (i);
  1632. }
  1633. } else if (selected != i && selected > -1 && (me.Flags == MouseFlags.ReportMousePosition ||
  1634. me.Flags == MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)) {
  1635. if (IsMenuOpen) {
  1636. if (!CloseMenu (true, false)) {
  1637. return true;
  1638. }
  1639. Activate (i);
  1640. }
  1641. } else {
  1642. if (IsMenuOpen)
  1643. Activate (i);
  1644. }
  1645. return true;
  1646. }
  1647. pos += leftPadding + Menus [i].TitleLength + rightPadding;
  1648. }
  1649. }
  1650. return false;
  1651. }
  1652. internal bool handled;
  1653. internal bool isContextMenuLoading;
  1654. internal bool HandleGrabView (MouseEvent me, View current)
  1655. {
  1656. if (Application.MouseGrabView != null) {
  1657. if (me.View is MenuBar || me.View is Menu) {
  1658. var mbar = GetMouseGrabViewInstance (me.View);
  1659. if (mbar != null) {
  1660. if (me.Flags == MouseFlags.Button1Clicked) {
  1661. mbar.CleanUp ();
  1662. Application.GrabMouse (me.View);
  1663. } else {
  1664. handled = false;
  1665. return false;
  1666. }
  1667. }
  1668. if (me.View != current) {
  1669. Application.UngrabMouse ();
  1670. var v = me.View;
  1671. Application.GrabMouse (v);
  1672. MouseEvent nme;
  1673. if (me.Y > -1) {
  1674. var newxy = v.ScreenToView (me.X, me.Y);
  1675. nme = new MouseEvent () {
  1676. X = newxy.X,
  1677. Y = newxy.Y,
  1678. Flags = me.Flags,
  1679. OfX = me.X - newxy.X,
  1680. OfY = me.Y - newxy.Y,
  1681. View = v
  1682. };
  1683. } else {
  1684. nme = new MouseEvent () {
  1685. X = me.X + current.Frame.X,
  1686. Y = 0,
  1687. Flags = me.Flags,
  1688. View = v
  1689. };
  1690. }
  1691. v.MouseEvent (nme);
  1692. return false;
  1693. }
  1694. } else if (!isContextMenuLoading && !(me.View is MenuBar || me.View is Menu)
  1695. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  1696. Application.UngrabMouse ();
  1697. if (IsMenuOpen)
  1698. CloseAllMenus ();
  1699. handled = false;
  1700. return false;
  1701. } else {
  1702. handled = false;
  1703. isContextMenuLoading = false;
  1704. return false;
  1705. }
  1706. } else if (!IsMenuOpen && (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked
  1707. || me.Flags == MouseFlags.Button1TripleClicked || me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))) {
  1708. Application.GrabMouse (current);
  1709. } else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu)) {
  1710. Application.GrabMouse (me.View);
  1711. } else {
  1712. handled = false;
  1713. return false;
  1714. }
  1715. handled = true;
  1716. return true;
  1717. }
  1718. MenuBar GetMouseGrabViewInstance (View view)
  1719. {
  1720. if (view == null || Application.MouseGrabView == null) {
  1721. return null;
  1722. }
  1723. MenuBar hostView = null;
  1724. if (view is MenuBar) {
  1725. hostView = (MenuBar)view;
  1726. } else if (view is Menu) {
  1727. hostView = ((Menu)view).host;
  1728. }
  1729. var grabView = Application.MouseGrabView;
  1730. MenuBar hostGrabView = null;
  1731. if (grabView is MenuBar) {
  1732. hostGrabView = (MenuBar)grabView;
  1733. } else if (grabView is Menu) {
  1734. hostGrabView = ((Menu)grabView).host;
  1735. }
  1736. return hostView != hostGrabView ? hostGrabView : null;
  1737. }
  1738. ///<inheritdoc/>
  1739. public override bool OnEnter (View view)
  1740. {
  1741. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  1742. return base.OnEnter (view);
  1743. }
  1744. }
  1745. /// <summary>
  1746. /// An <see cref="EventArgs"/> which allows passing a cancelable menu opening event or replacing with a new <see cref="MenuBarItem"/>.
  1747. /// </summary>
  1748. public class MenuOpeningEventArgs : EventArgs {
  1749. /// <summary>
  1750. /// The current <see cref="MenuBarItem"/> parent.
  1751. /// </summary>
  1752. public MenuBarItem CurrentMenu { get; }
  1753. /// <summary>
  1754. /// The new <see cref="MenuBarItem"/> to be replaced.
  1755. /// </summary>
  1756. public MenuBarItem NewMenuBarItem { get; set; }
  1757. /// <summary>
  1758. /// Flag that allows the cancellation of the event. If set to <see langword="true"/> in the
  1759. /// event handler, the event will be canceled.
  1760. /// </summary>
  1761. public bool Cancel { get; set; }
  1762. /// <summary>
  1763. /// Initializes a new instance of <see cref="MenuOpeningEventArgs"/>.
  1764. /// </summary>
  1765. /// <param name="currentMenu">The current <see cref="MenuBarItem"/> parent.</param>
  1766. public MenuOpeningEventArgs (MenuBarItem currentMenu)
  1767. {
  1768. CurrentMenu = currentMenu;
  1769. }
  1770. }
  1771. /// <summary>
  1772. /// An <see cref="EventArgs"/> which allows passing a cancelable menu closing event.
  1773. /// </summary>
  1774. public class MenuClosingEventArgs : EventArgs {
  1775. /// <summary>
  1776. /// The current <see cref="MenuBarItem"/> parent.
  1777. /// </summary>
  1778. public MenuBarItem CurrentMenu { get; }
  1779. /// <summary>
  1780. /// Indicates whether the current menu will reopen.
  1781. /// </summary>
  1782. public bool Reopen { get; }
  1783. /// <summary>
  1784. /// Indicates whether the current menu is a sub-menu.
  1785. /// </summary>
  1786. public bool IsSubMenu { get; }
  1787. /// <summary>
  1788. /// Flag that allows the cancellation of the event. If set to <see langword="true"/> in the
  1789. /// event handler, the event will be canceled.
  1790. /// </summary>
  1791. public bool Cancel { get; set; }
  1792. /// <summary>
  1793. /// Initializes a new instance of <see cref="MenuClosingEventArgs"/>.
  1794. /// </summary>
  1795. /// <param name="currentMenu">The current <see cref="MenuBarItem"/> parent.</param>
  1796. /// <param name="reopen">Whether the current menu will reopen.</param>
  1797. /// <param name="isSubMenu">Indicates whether it is a sub-menu.</param>
  1798. public MenuClosingEventArgs (MenuBarItem currentMenu, bool reopen, bool isSubMenu)
  1799. {
  1800. CurrentMenu = currentMenu;
  1801. Reopen = reopen;
  1802. IsSubMenu = isSubMenu;
  1803. }
  1804. }
  1805. }