Menu.cs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094
  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]?.IsEnabled () == true) {
  375. current = i;
  376. break;
  377. }
  378. }
  379. ColorScheme = host.ColorScheme;
  380. CanFocus = true;
  381. WantMousePositionReports = host.WantMousePositionReports;
  382. }
  383. if (Application.Current != null) {
  384. Application.Current.Resized += Current_Resized;
  385. }
  386. // Things this view knows how to do
  387. AddCommand (Command.LineUp, () => MoveUp ());
  388. AddCommand (Command.LineDown, () => MoveDown ());
  389. AddCommand (Command.Left, () => { this.host.PreviousMenu (true); return true; });
  390. AddCommand (Command.Right, () => {
  391. this.host.NextMenu (!this.barItems.IsTopLevel || (this.barItems.Children != null
  392. && this.barItems.Children.Length > 0 && current > -1
  393. && current < this.barItems.Children.Length && this.barItems.Children [current].IsFromSubMenu),
  394. this.barItems.Children != null && this.barItems.Children.Length > 0 && current > -1
  395. && host.UseSubMenusSingleFrame && this.barItems.SubMenu (this.barItems.Children [current]) != null);
  396. return true;
  397. });
  398. AddCommand (Command.Cancel, () => { CloseAllMenus (); return true; });
  399. AddCommand (Command.Accept, () => { RunSelected (); return true; });
  400. // Default keybindings for this view
  401. AddKeyBinding (Key.CursorUp, Command.LineUp);
  402. AddKeyBinding (Key.CursorDown, Command.LineDown);
  403. AddKeyBinding (Key.CursorLeft, Command.Left);
  404. AddKeyBinding (Key.CursorRight, Command.Right);
  405. AddKeyBinding (Key.Esc, Command.Cancel);
  406. AddKeyBinding (Key.Enter, Command.Accept);
  407. }
  408. private void Current_Resized (Size obj)
  409. {
  410. if (host.IsMenuOpen) {
  411. host.CloseAllMenus ();
  412. }
  413. }
  414. internal Attribute DetermineColorSchemeFor (MenuItem item, int index)
  415. {
  416. if (item != null) {
  417. if (index == current) return ColorScheme.Focus;
  418. if (!item.IsEnabled ()) return ColorScheme.Disabled;
  419. }
  420. return GetNormalColor ();
  421. }
  422. // Draws the Menu, within the Frame
  423. public override void Redraw (Rect bounds)
  424. {
  425. Driver.SetAttribute (GetNormalColor ());
  426. DrawFrame (Bounds, padding: 0, fill: true);
  427. for (int i = Bounds.Y; i < barItems.Children.Length; i++) {
  428. if (i < 0)
  429. continue;
  430. var item = barItems.Children [i];
  431. Driver.SetAttribute (item == null ? GetNormalColor ()
  432. : i == current ? ColorScheme.Focus : GetNormalColor ());
  433. if (item == null) {
  434. Move (0, i + 1);
  435. Driver.AddRune (Driver.LeftTee);
  436. } else if (Frame.X + 1 < Driver.Cols)
  437. Move (1, i + 1);
  438. Driver.SetAttribute (DetermineColorSchemeFor (item, i));
  439. for (int p = Bounds.X; p < Frame.Width - 2; p++) { // This - 2 is for the border
  440. if (p < 0)
  441. continue;
  442. if (item == null)
  443. Driver.AddRune (Driver.HLine);
  444. else if (i == 0 && p == 0 && host.UseSubMenusSingleFrame && item.Parent.Parent != null)
  445. Driver.AddRune (Driver.LeftArrow);
  446. // This `- 3` is left border + right border + one row in from right
  447. else if (p == Frame.Width - 3 && barItems.SubMenu (barItems.Children [i]) != null)
  448. Driver.AddRune (Driver.RightArrow);
  449. else
  450. Driver.AddRune (' ');
  451. }
  452. if (item == null) {
  453. if (SuperView?.Frame.Right - Frame.X > Frame.Width - 1) {
  454. Move (Frame.Width - 1, i + 1);
  455. Driver.AddRune (Driver.RightTee);
  456. }
  457. continue;
  458. }
  459. ustring textToDraw;
  460. var checkChar = Driver.Selected;
  461. var uncheckedChar = Driver.UnSelected;
  462. if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked)) {
  463. checkChar = Driver.Checked;
  464. uncheckedChar = Driver.UnChecked;
  465. }
  466. // Support Checked even though CheckType wasn't set
  467. if (item.Checked) {
  468. textToDraw = ustring.Make (new Rune [] { checkChar, ' ' }) + item.Title;
  469. } else if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked) || item.CheckType.HasFlag (MenuItemCheckStyle.Radio)) {
  470. textToDraw = ustring.Make (new Rune [] { uncheckedChar, ' ' }) + item.Title;
  471. } else {
  472. textToDraw = item.Title;
  473. }
  474. ViewToScreen (2, i + 1, out int vtsCol, out _, false);
  475. if (vtsCol < Driver.Cols) {
  476. Move (2, i + 1);
  477. if (!item.IsEnabled ()) {
  478. DrawHotString (textToDraw, ColorScheme.Disabled, ColorScheme.Disabled);
  479. } else if (i == 0 && host.UseSubMenusSingleFrame && item.Parent.Parent != null) {
  480. var tf = new TextFormatter () {
  481. Alignment = TextAlignment.Centered,
  482. HotKeySpecifier = MenuBar.HotKeySpecifier,
  483. Text = textToDraw
  484. };
  485. // The -3 is left/right border + one space (not sure what for)
  486. tf.Draw (ViewToScreen (new Rect (2, i + 1, Frame.Width - 3, 1)),
  487. i == current ? ColorScheme.Focus : GetNormalColor (),
  488. i == current ? ColorScheme.HotFocus : ColorScheme.HotNormal,
  489. SuperView == null ? default : SuperView.ViewToScreen (SuperView.Bounds));
  490. } else {
  491. DrawHotString (textToDraw,
  492. i == current ? ColorScheme.HotFocus : ColorScheme.HotNormal,
  493. i == current ? ColorScheme.Focus : GetNormalColor ());
  494. }
  495. // The help string
  496. var l = item.ShortcutTag.ConsoleWidth == 0 ? item.Help.ConsoleWidth : item.Help.ConsoleWidth + item.ShortcutTag.ConsoleWidth + 2;
  497. var col = Frame.Width - l - 2;
  498. ViewToScreen (col, i + 1, out vtsCol, out _, false);
  499. if (vtsCol < Driver.Cols) {
  500. Move (col, 1 + i);
  501. Driver.AddStr (item.Help);
  502. // The shortcut tag string
  503. if (!item.ShortcutTag.IsEmpty) {
  504. l = item.ShortcutTag.ConsoleWidth;
  505. Move (Frame.Width - l - 2, 1 + i);
  506. Driver.AddStr (item.ShortcutTag);
  507. }
  508. }
  509. }
  510. }
  511. PositionCursor ();
  512. }
  513. public override void PositionCursor ()
  514. {
  515. if (host == null || host.IsMenuOpen)
  516. if (barItems.IsTopLevel) {
  517. host.PositionCursor ();
  518. } else
  519. Move (2, 1 + current);
  520. else
  521. host.PositionCursor ();
  522. }
  523. public void Run (Action action)
  524. {
  525. if (action == null || host == null)
  526. return;
  527. Application.UngrabMouse ();
  528. host.CloseAllMenus ();
  529. Application.Refresh ();
  530. host.Run (action);
  531. }
  532. public override bool OnLeave (View view)
  533. {
  534. return host.OnLeave (view);
  535. }
  536. public override bool OnKeyDown (KeyEvent keyEvent)
  537. {
  538. if (keyEvent.IsAlt) {
  539. host.CloseAllMenus ();
  540. return true;
  541. }
  542. return false;
  543. }
  544. public override bool ProcessHotKey (KeyEvent keyEvent)
  545. {
  546. // To ncurses simulate a AltMask key pressing Alt+Space because
  547. // it can�t detect an alone special key down was pressed.
  548. if (keyEvent.IsAlt && keyEvent.Key == Key.AltMask) {
  549. OnKeyDown (keyEvent);
  550. return true;
  551. }
  552. return false;
  553. }
  554. public override bool ProcessKey (KeyEvent kb)
  555. {
  556. var result = InvokeKeybindings (kb);
  557. if (result != null)
  558. return (bool)result;
  559. // TODO: rune-ify
  560. if (barItems.Children != null && Char.IsLetterOrDigit ((char)kb.KeyValue)) {
  561. var x = Char.ToUpper ((char)kb.KeyValue);
  562. var idx = -1;
  563. foreach (var item in barItems.Children) {
  564. idx++;
  565. if (item == null) continue;
  566. if (item.IsEnabled () && item.HotKey == x) {
  567. current = idx;
  568. RunSelected ();
  569. return true;
  570. }
  571. }
  572. }
  573. return host.ProcessHotKey (kb);
  574. }
  575. void RunSelected ()
  576. {
  577. if (barItems.IsTopLevel) {
  578. Run (barItems.Action);
  579. } else if (current > -1 && barItems.Children [current].Action != null) {
  580. Run (barItems.Children [current].Action);
  581. } else if (current == 0 && host.UseSubMenusSingleFrame
  582. && barItems.Children [current].Parent.Parent != null) {
  583. host.PreviousMenu (barItems.Children [current].Parent.IsFromSubMenu, true);
  584. } else if (current > -1 && barItems.SubMenu (barItems.Children [current]) != null) {
  585. CheckSubMenu ();
  586. }
  587. }
  588. void CloseAllMenus ()
  589. {
  590. Application.UngrabMouse ();
  591. host.CloseAllMenus ();
  592. }
  593. bool MoveDown ()
  594. {
  595. if (barItems.IsTopLevel) {
  596. return true;
  597. }
  598. bool disabled;
  599. do {
  600. current++;
  601. if (current >= barItems.Children.Length) {
  602. current = 0;
  603. }
  604. if (this != host.openCurrentMenu && barItems.Children [current]?.IsFromSubMenu == true && host.selectedSub > -1) {
  605. host.PreviousMenu (true);
  606. host.SelectEnabledItem (barItems.Children, current, out current);
  607. host.openCurrentMenu = this;
  608. }
  609. var item = barItems.Children [current];
  610. if (item?.IsEnabled () != true) {
  611. disabled = true;
  612. } else {
  613. disabled = false;
  614. }
  615. if (!host.UseSubMenusSingleFrame && host.UseKeysUpDownAsKeysLeftRight && barItems.SubMenu (barItems.Children [current]) != null &&
  616. !disabled && host.IsMenuOpen) {
  617. if (!CheckSubMenu ())
  618. return false;
  619. break;
  620. }
  621. if (!host.IsMenuOpen) {
  622. host.OpenMenu (host.selected);
  623. }
  624. } while (barItems.Children [current] == null || disabled);
  625. SetNeedsDisplay ();
  626. SetParentSetNeedsDisplay ();
  627. if (!host.UseSubMenusSingleFrame)
  628. host.OnMenuOpened ();
  629. return true;
  630. }
  631. bool MoveUp ()
  632. {
  633. if (barItems.IsTopLevel || current == -1) {
  634. return true;
  635. }
  636. bool disabled;
  637. do {
  638. current--;
  639. if (host.UseKeysUpDownAsKeysLeftRight && !host.UseSubMenusSingleFrame) {
  640. if ((current == -1 || this != host.openCurrentMenu) && barItems.Children [current + 1].IsFromSubMenu && host.selectedSub > -1) {
  641. current++;
  642. host.PreviousMenu (true);
  643. if (current > 0) {
  644. current--;
  645. host.openCurrentMenu = this;
  646. }
  647. break;
  648. }
  649. }
  650. if (current < 0)
  651. current = barItems.Children.Length - 1;
  652. if (!host.SelectEnabledItem (barItems.Children, current, out current, false)) {
  653. current = 0;
  654. if (!host.SelectEnabledItem (barItems.Children, current, out current) && !host.CloseMenu (false)) {
  655. return false;
  656. }
  657. break;
  658. }
  659. var item = barItems.Children [current];
  660. if (item?.IsEnabled () != true) {
  661. disabled = true;
  662. } else {
  663. disabled = false;
  664. }
  665. if (!host.UseSubMenusSingleFrame && host.UseKeysUpDownAsKeysLeftRight && barItems.SubMenu (barItems.Children [current]) != null &&
  666. !disabled && host.IsMenuOpen) {
  667. if (!CheckSubMenu ())
  668. return false;
  669. break;
  670. }
  671. } while (barItems.Children [current] == null || disabled);
  672. SetNeedsDisplay ();
  673. SetParentSetNeedsDisplay ();
  674. if (!host.UseSubMenusSingleFrame)
  675. host.OnMenuOpened ();
  676. return true;
  677. }
  678. private void SetParentSetNeedsDisplay ()
  679. {
  680. if (host.openSubMenu != null) {
  681. foreach (var menu in host.openSubMenu) {
  682. menu.SetNeedsDisplay ();
  683. }
  684. }
  685. host?.openMenu.SetNeedsDisplay ();
  686. host.SetNeedsDisplay ();
  687. }
  688. public override bool MouseEvent (MouseEvent me)
  689. {
  690. if (!host.handled && !host.HandleGrabView (me, this)) {
  691. return false;
  692. }
  693. host.handled = false;
  694. bool disabled;
  695. if (me.Flags == MouseFlags.Button1Clicked) {
  696. disabled = false;
  697. if (me.Y < 1)
  698. return true;
  699. var meY = me.Y - 1;
  700. if (meY >= barItems.Children.Length)
  701. return true;
  702. var item = barItems.Children [meY];
  703. if (item == null || !item.IsEnabled ()) disabled = true;
  704. if (disabled) return true;
  705. current = meY;
  706. if (item != null && !disabled)
  707. RunSelected ();
  708. return true;
  709. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked ||
  710. me.Flags == MouseFlags.Button1TripleClicked || me.Flags == MouseFlags.ReportMousePosition ||
  711. me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  712. disabled = false;
  713. if (me.Y < 1 || me.Y - 1 >= barItems.Children.Length) {
  714. return true;
  715. }
  716. var item = barItems.Children [me.Y - 1];
  717. if (item == null) return true;
  718. if (item == null || !item.IsEnabled ()) disabled = true;
  719. if (item != null && !disabled)
  720. current = me.Y - 1;
  721. if (host.UseSubMenusSingleFrame || !CheckSubMenu ()) {
  722. SetNeedsDisplay ();
  723. SetParentSetNeedsDisplay ();
  724. return true;
  725. }
  726. host.OnMenuOpened ();
  727. return true;
  728. }
  729. return false;
  730. }
  731. internal bool CheckSubMenu ()
  732. {
  733. if (current == -1 || barItems.Children [current] == null) {
  734. return true;
  735. }
  736. var subMenu = barItems.SubMenu (barItems.Children [current]);
  737. if (subMenu != null) {
  738. int pos = -1;
  739. if (host.openSubMenu != null) {
  740. pos = host.openSubMenu.FindIndex (o => o?.barItems == subMenu);
  741. }
  742. if (pos == -1 && this != host.openCurrentMenu && subMenu.Children != host.openCurrentMenu.barItems.Children
  743. && !host.CloseMenu (false, true)) {
  744. return false;
  745. }
  746. host.Activate (host.selected, pos, subMenu);
  747. } else if (host.openSubMenu?.Count == 0 || host.openSubMenu?.Last ().barItems.IsSubMenuOf (barItems.Children [current]) == false) {
  748. return host.CloseMenu (false, true);
  749. } else {
  750. SetNeedsDisplay ();
  751. SetParentSetNeedsDisplay ();
  752. }
  753. return true;
  754. }
  755. int GetSubMenuIndex (MenuBarItem subMenu)
  756. {
  757. int pos = -1;
  758. if (this != null && Subviews.Count > 0) {
  759. Menu v = null;
  760. foreach (var menu in Subviews) {
  761. if (((Menu)menu).barItems == subMenu)
  762. v = (Menu)menu;
  763. }
  764. if (v != null)
  765. pos = Subviews.IndexOf (v);
  766. }
  767. return pos;
  768. }
  769. ///<inheritdoc/>
  770. public override bool OnEnter (View view)
  771. {
  772. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  773. return base.OnEnter (view);
  774. }
  775. protected override void Dispose (bool disposing)
  776. {
  777. if (Application.Current != null) {
  778. Application.Current.Resized -= Current_Resized;
  779. }
  780. base.Dispose (disposing);
  781. }
  782. }
  783. /// <summary>
  784. /// <para>
  785. /// Provides a menu bar that spans the top of a <see cref="Toplevel"/> View with drop-down and cascading menus.
  786. /// </para>
  787. /// <para>
  788. /// By default, any sub-sub-menus (sub-menus of the <see cref="MenuItem"/>s added to <see cref="MenuBarItem"/>s)
  789. /// are displayed in a cascading manner, where each sub-sub-menu pops out of the sub-menu frame
  790. /// (either to the right or left, depending on where the sub-menu is relative to the edge of the screen). By setting
  791. /// <see cref="UseSubMenusSingleFrame"/> to <see langword="true"/>, this behavior can be changed such that all sub-sub-menus are
  792. /// drawn within a single frame below the MenuBar.
  793. /// </para>
  794. /// </summary>
  795. /// <remarks>
  796. /// <para>
  797. /// The <see cref="MenuBar"/> appears on the first row of the parent <see cref="Toplevel"/> View and uses the full width.
  798. /// </para>
  799. /// <para>
  800. /// The <see cref="MenuBar"/> provides global hotkeys for the application. See <see cref="MenuItem.HotKey"/>.
  801. /// </para>
  802. /// <para>
  803. /// See also: <see cref="ContextMenu"/>
  804. /// </para>
  805. /// </remarks>
  806. public class MenuBar : View {
  807. internal int selected;
  808. internal int selectedSub;
  809. /// <summary>
  810. /// Gets or sets the array of <see cref="MenuBarItem"/>s for the menu. Only set this after the <see cref="MenuBar"/> is visible.
  811. /// </summary>
  812. /// <value>The menu array.</value>
  813. public MenuBarItem [] Menus { get; set; }
  814. private bool useKeysUpDownAsKeysLeftRight = false;
  815. /// <summary>
  816. /// Used for change the navigation key style.
  817. /// </summary>
  818. public bool UseKeysUpDownAsKeysLeftRight {
  819. get => useKeysUpDownAsKeysLeftRight;
  820. set {
  821. useKeysUpDownAsKeysLeftRight = value;
  822. if (value && UseSubMenusSingleFrame) {
  823. UseSubMenusSingleFrame = false;
  824. SetNeedsDisplay ();
  825. }
  826. }
  827. }
  828. static ustring shortcutDelimiter = "+";
  829. /// <summary>
  830. /// Sets or gets the shortcut delimiter separator. The default is "+".
  831. /// </summary>
  832. public static ustring ShortcutDelimiter {
  833. get => shortcutDelimiter;
  834. set {
  835. if (shortcutDelimiter != value) {
  836. shortcutDelimiter = value == ustring.Empty ? " " : value;
  837. }
  838. }
  839. }
  840. /// <summary>
  841. /// The specifier character for the hotkey to all menus.
  842. /// </summary>
  843. new public static Rune HotKeySpecifier => '_';
  844. private bool useSubMenusSingleFrame;
  845. /// <summary>
  846. /// Gets or sets if the sub-menus must be displayed in a single or multiple frames.
  847. /// <para>
  848. /// By default any sub-sub-menus (sub-menus of the main <see cref="MenuItem"/>s) are displayed in a cascading manner,
  849. /// where each sub-sub-menu pops out of the sub-menu frame
  850. /// (either to the right or left, depending on where the sub-menu is relative to the edge of the screen). By setting
  851. /// <see cref="UseSubMenusSingleFrame"/> to <see langword="true"/>, this behavior can be changed such that all sub-sub-menus are
  852. /// drawn within a single frame below the MenuBar.
  853. /// </para>
  854. /// </summary>
  855. public bool UseSubMenusSingleFrame {
  856. get => useSubMenusSingleFrame;
  857. set {
  858. useSubMenusSingleFrame = value;
  859. if (value && UseKeysUpDownAsKeysLeftRight) {
  860. useKeysUpDownAsKeysLeftRight = false;
  861. SetNeedsDisplay ();
  862. }
  863. }
  864. }
  865. /// <summary>
  866. /// The <see cref="Gui.Key"/> used to activate the menu bar by keyboard.
  867. /// </summary>
  868. public Key Key { get; set; } = Key.F9;
  869. ///<inheritdoc/>
  870. public override bool Visible {
  871. get => base.Visible;
  872. set {
  873. base.Visible = value;
  874. if (!value) {
  875. CloseAllMenus ();
  876. }
  877. }
  878. }
  879. /// <summary>
  880. /// Initializes a new instance of the <see cref="MenuBar"/>.
  881. /// </summary>
  882. public MenuBar () : this (new MenuBarItem [] { }) { }
  883. /// <summary>
  884. /// Initializes a new instance of the <see cref="MenuBar"/> class with the specified set of toplevel menu items.
  885. /// </summary>
  886. /// <param name="menus">Individual menu items; a null item will result in a separator being drawn.</param>
  887. public MenuBar (MenuBarItem [] menus) : base ()
  888. {
  889. X = 0;
  890. Y = 0;
  891. Width = Dim.Fill ();
  892. Height = 1;
  893. Menus = menus;
  894. //CanFocus = true;
  895. selected = -1;
  896. selectedSub = -1;
  897. ColorScheme = Colors.Menu;
  898. WantMousePositionReports = true;
  899. IsMenuOpen = false;
  900. // Things this view knows how to do
  901. AddCommand (Command.Left, () => { MoveLeft (); return true; });
  902. AddCommand (Command.Right, () => { MoveRight (); return true; });
  903. AddCommand (Command.Cancel, () => { CloseMenuBar (); return true; });
  904. AddCommand (Command.Accept, () => { ProcessMenu (selected, Menus [selected]); return true; });
  905. // Default keybindings for this view
  906. AddKeyBinding (Key.CursorLeft, Command.Left);
  907. AddKeyBinding (Key.CursorRight, Command.Right);
  908. AddKeyBinding (Key.Esc, Command.Cancel);
  909. AddKeyBinding (Key.C | Key.CtrlMask, Command.Cancel);
  910. AddKeyBinding (Key.CursorDown, Command.Accept);
  911. AddKeyBinding (Key.Enter, Command.Accept);
  912. }
  913. bool openedByAltKey;
  914. bool isCleaning;
  915. ///<inheritdoc/>
  916. public override bool OnLeave (View view)
  917. {
  918. if ((!(view is MenuBar) && !(view is Menu) || !(view is MenuBar) && !(view is Menu) && openMenu != null) && !isCleaning && !reopen) {
  919. CleanUp ();
  920. return true;
  921. }
  922. return false;
  923. }
  924. ///<inheritdoc/>
  925. public override bool OnKeyDown (KeyEvent keyEvent)
  926. {
  927. if (keyEvent.IsAlt || (keyEvent.IsCtrl && keyEvent.Key == (Key.CtrlMask | Key.Space))) {
  928. openedByAltKey = true;
  929. SetNeedsDisplay ();
  930. openedByHotKey = false;
  931. }
  932. return false;
  933. }
  934. ///<inheritdoc/>
  935. public override bool OnKeyUp (KeyEvent keyEvent)
  936. {
  937. if (keyEvent.IsAlt || keyEvent.Key == Key.AltMask || (keyEvent.IsCtrl && keyEvent.Key == (Key.CtrlMask | Key.Space))) {
  938. // User pressed Alt - this may be a precursor to a menu accelerator (e.g. Alt-F)
  939. if (openedByAltKey && !IsMenuOpen && openMenu == null && (((uint)keyEvent.Key & (uint)Key.CharMask) == 0
  940. || ((uint)keyEvent.Key & (uint)Key.CharMask) == (uint)Key.Space)) {
  941. // There's no open menu, the first menu item should be highlight.
  942. // The right way to do this is to SetFocus(MenuBar), but for some reason
  943. // that faults.
  944. var mbar = GetMouseGrabViewInstance (this);
  945. if (mbar != null) {
  946. mbar.CleanUp ();
  947. }
  948. //Activate (0);
  949. //StartMenu ();
  950. IsMenuOpen = true;
  951. selected = 0;
  952. CanFocus = true;
  953. lastFocused = SuperView == null ? Application.Current.MostFocused : SuperView.MostFocused;
  954. SetFocus ();
  955. SetNeedsDisplay ();
  956. Application.GrabMouse (this);
  957. } else if (!openedByHotKey) {
  958. // There's an open menu. If this Alt key-up is a pre-cursor to an accelerator
  959. // we don't want to close the menu because it'll flash.
  960. // How to deal with that?
  961. CleanUp ();
  962. }
  963. return true;
  964. }
  965. return false;
  966. }
  967. internal void CleanUp ()
  968. {
  969. isCleaning = true;
  970. if (openMenu != null) {
  971. CloseAllMenus ();
  972. }
  973. openedByAltKey = false;
  974. IsMenuOpen = false;
  975. selected = -1;
  976. CanFocus = false;
  977. if (lastFocused != null) {
  978. lastFocused.SetFocus ();
  979. }
  980. SetNeedsDisplay ();
  981. Application.UngrabMouse ();
  982. isCleaning = false;
  983. }
  984. // The column where the MenuBar starts
  985. static int xOrigin = 0;
  986. // Spaces before the Title
  987. static int leftPadding = 1;
  988. // Spaces after the Title
  989. static int rightPadding = 1;
  990. // Spaces after the submenu Title, before Help
  991. static int parensAroundHelp = 3;
  992. ///<inheritdoc/>
  993. public override void Redraw (Rect bounds)
  994. {
  995. Move (0, 0);
  996. Driver.SetAttribute (GetNormalColor ());
  997. for (int i = 0; i < Frame.Width; i++)
  998. Driver.AddRune (' ');
  999. Move (1, 0);
  1000. int pos = 0;
  1001. for (int i = 0; i < Menus.Length; i++) {
  1002. var menu = Menus [i];
  1003. Move (pos, 0);
  1004. Attribute hotColor, normalColor;
  1005. if (i == selected && IsMenuOpen) {
  1006. hotColor = i == selected ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  1007. normalColor = i == selected ? ColorScheme.Focus : GetNormalColor ();
  1008. } else {
  1009. hotColor = ColorScheme.HotNormal;
  1010. normalColor = GetNormalColor ();
  1011. }
  1012. // Note Help on MenuBar is drawn with parens around it
  1013. DrawHotString (menu.Help.IsEmpty ? $" {menu.Title} " : $" {menu.Title} ({menu.Help}) ", hotColor, normalColor);
  1014. pos += leftPadding + menu.TitleLength + (menu.Help.ConsoleWidth > 0 ? leftPadding + menu.Help.ConsoleWidth + parensAroundHelp : 0) + rightPadding;
  1015. }
  1016. PositionCursor ();
  1017. }
  1018. ///<inheritdoc/>
  1019. public override void PositionCursor ()
  1020. {
  1021. if (selected == -1 && HasFocus && Menus.Length > 0) {
  1022. selected = 0;
  1023. }
  1024. int pos = 0;
  1025. for (int i = 0; i < Menus.Length; i++) {
  1026. if (i == selected) {
  1027. pos++;
  1028. Move (pos + 1, 0);
  1029. return;
  1030. } else {
  1031. pos += leftPadding + Menus [i].TitleLength + (Menus [i].Help.ConsoleWidth > 0 ? Menus [i].Help.ConsoleWidth + parensAroundHelp : 0) + rightPadding;
  1032. }
  1033. }
  1034. }
  1035. void Selected (MenuItem item)
  1036. {
  1037. var action = item.Action;
  1038. if (action == null)
  1039. return;
  1040. Application.UngrabMouse ();
  1041. CloseAllMenus ();
  1042. Application.Refresh ();
  1043. Run (action);
  1044. }
  1045. internal void Run (Action action)
  1046. {
  1047. Application.MainLoop.AddIdle (() => {
  1048. action ();
  1049. return false;
  1050. });
  1051. CloseAllMenus ();
  1052. }
  1053. /// <summary>
  1054. /// Raised as a menu is opening.
  1055. /// </summary>
  1056. public event Action<MenuOpeningEventArgs> MenuOpening;
  1057. /// <summary>
  1058. /// Raised when a menu is opened.
  1059. /// </summary>
  1060. public event Action<MenuItem> MenuOpened;
  1061. /// <summary>
  1062. /// Raised when a menu is closing passing <see cref="MenuClosingEventArgs"/>.
  1063. /// </summary>
  1064. public event Action<MenuClosingEventArgs> MenuClosing;
  1065. /// <summary>
  1066. /// Raised when all the menu is closed.
  1067. /// </summary>
  1068. public event Action MenuAllClosed;
  1069. internal Menu openMenu;
  1070. Menu ocm;
  1071. internal Menu openCurrentMenu {
  1072. get => ocm;
  1073. set {
  1074. if (ocm != value) {
  1075. ocm = value;
  1076. if (ocm.current > -1) {
  1077. OnMenuOpened ();
  1078. }
  1079. }
  1080. }
  1081. }
  1082. internal List<Menu> openSubMenu;
  1083. View previousFocused;
  1084. internal bool isMenuOpening;
  1085. internal bool isMenuClosing;
  1086. /// <summary>
  1087. /// <see langword="true"/> if the menu is open; otherwise <see langword="true"/>.
  1088. /// </summary>
  1089. public bool IsMenuOpen { get; protected set; }
  1090. /// <summary>
  1091. /// Virtual method that will invoke the <see cref="MenuOpening"/> event if it's defined.
  1092. /// </summary>
  1093. /// <param name="currentMenu">The current menu to be replaced.</param>
  1094. /// <returns>Returns the <see cref="MenuOpeningEventArgs"/></returns>
  1095. public virtual MenuOpeningEventArgs OnMenuOpening (MenuBarItem currentMenu)
  1096. {
  1097. var ev = new MenuOpeningEventArgs (currentMenu);
  1098. MenuOpening?.Invoke (ev);
  1099. return ev;
  1100. }
  1101. /// <summary>
  1102. /// Virtual method that will invoke the <see cref="MenuOpened"/> event if it's defined.
  1103. /// </summary>
  1104. public virtual void OnMenuOpened ()
  1105. {
  1106. MenuItem mi = null;
  1107. if (openCurrentMenu.barItems.Children != null && openCurrentMenu.barItems.Children.Length > 0
  1108. && openCurrentMenu?.current > -1) {
  1109. mi = openCurrentMenu.barItems.Children [openCurrentMenu.current];
  1110. } else if (openCurrentMenu.barItems.IsTopLevel) {
  1111. mi = openCurrentMenu.barItems;
  1112. } else if (openCurrentMenu?.current > -1) {
  1113. mi = openMenu.barItems.Children [openMenu.current];
  1114. }
  1115. MenuOpened?.Invoke (mi);
  1116. }
  1117. /// <summary>
  1118. /// Virtual method that will invoke the <see cref="MenuClosing"/>.
  1119. /// </summary>
  1120. /// <param name="currentMenu">The current menu to be closed.</param>
  1121. /// <param name="reopen">Whether the current menu will be reopen.</param>
  1122. /// <param name="isSubMenu">Whether is a sub-menu or not.</param>
  1123. public virtual MenuClosingEventArgs OnMenuClosing (MenuBarItem currentMenu, bool reopen, bool isSubMenu)
  1124. {
  1125. var ev = new MenuClosingEventArgs (currentMenu, reopen, isSubMenu);
  1126. MenuClosing?.Invoke (ev);
  1127. return ev;
  1128. }
  1129. /// <summary>
  1130. /// Virtual method that will invoke the <see cref="MenuAllClosed"/>.
  1131. /// </summary>
  1132. public virtual void OnMenuAllClosed ()
  1133. {
  1134. MenuAllClosed?.Invoke ();
  1135. }
  1136. View lastFocused;
  1137. /// <summary>
  1138. /// Gets the view that was last focused before opening the menu.
  1139. /// </summary>
  1140. public View LastFocused { get; private set; }
  1141. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem subMenu = null)
  1142. {
  1143. isMenuOpening = true;
  1144. var newMenu = OnMenuOpening (Menus [index]);
  1145. if (newMenu.Cancel) {
  1146. isMenuOpening = false;
  1147. return;
  1148. }
  1149. if (newMenu.NewMenuBarItem != null) {
  1150. Menus [index] = newMenu.NewMenuBarItem;
  1151. }
  1152. int pos = 0;
  1153. switch (subMenu) {
  1154. case null:
  1155. // Open a submenu below a MenuBar
  1156. lastFocused = lastFocused ?? (SuperView == null ? Application.Current.MostFocused : SuperView.MostFocused);
  1157. if (openSubMenu != null && !CloseMenu (false, true))
  1158. return;
  1159. if (openMenu != null) {
  1160. if (SuperView == null) {
  1161. Application.Current.Remove (openMenu);
  1162. } else {
  1163. SuperView.Remove (openMenu);
  1164. }
  1165. openMenu.Dispose ();
  1166. }
  1167. // This positions the submenu horizontally aligned with the first character of the
  1168. // menu it belongs to's text
  1169. for (int i = 0; i < index; i++)
  1170. pos += Menus [i].TitleLength + (Menus [i].Help.ConsoleWidth > 0 ? Menus [i].Help.ConsoleWidth + 2 : 0) + leftPadding + rightPadding;
  1171. openMenu = new Menu (this, Frame.X + pos, Frame.Y + 1, Menus [index]);
  1172. openCurrentMenu = openMenu;
  1173. openCurrentMenu.previousSubFocused = openMenu;
  1174. if (SuperView == null) {
  1175. Application.Current.Add (openMenu);
  1176. } else {
  1177. SuperView.Add (openMenu);
  1178. }
  1179. openMenu.SetFocus ();
  1180. break;
  1181. default:
  1182. // Opens a submenu next to another submenu (openSubMenu)
  1183. if (openSubMenu == null)
  1184. openSubMenu = new List<Menu> ();
  1185. if (sIndex > -1) {
  1186. RemoveSubMenu (sIndex);
  1187. } else {
  1188. var last = openSubMenu.Count > 0 ? openSubMenu.Last () : openMenu;
  1189. if (!UseSubMenusSingleFrame) {
  1190. openCurrentMenu = new Menu (this, last.Frame.Left + last.Frame.Width, last.Frame.Top + 1 + last.current, subMenu, last);
  1191. } else {
  1192. var first = openSubMenu.Count > 0 ? openSubMenu.First () : openMenu;
  1193. var mbi = new MenuItem [2 + subMenu.Children.Length];
  1194. mbi [0] = new MenuItem () { Title = subMenu.Title, Parent = subMenu };
  1195. mbi [1] = null;
  1196. for (int j = 0; j < subMenu.Children.Length; j++) {
  1197. mbi [j + 2] = subMenu.Children [j];
  1198. }
  1199. var newSubMenu = new MenuBarItem (mbi);
  1200. openCurrentMenu = new Menu (this, first.Frame.Left, first.Frame.Top, newSubMenu);
  1201. last.Visible = false;
  1202. Application.GrabMouse (openCurrentMenu);
  1203. }
  1204. openCurrentMenu.previousSubFocused = last.previousSubFocused;
  1205. openSubMenu.Add (openCurrentMenu);
  1206. if (SuperView == null) {
  1207. Application.Current.Add (openCurrentMenu);
  1208. } else {
  1209. SuperView.Add (openCurrentMenu);
  1210. }
  1211. }
  1212. selectedSub = openSubMenu.Count - 1;
  1213. if (selectedSub > -1 && SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  1214. openCurrentMenu.SetFocus ();
  1215. }
  1216. break;
  1217. }
  1218. isMenuOpening = false;
  1219. IsMenuOpen = true;
  1220. }
  1221. /// <summary>
  1222. /// Opens the Menu programatically, as though the F9 key were pressed.
  1223. /// </summary>
  1224. public void OpenMenu ()
  1225. {
  1226. var mbar = GetMouseGrabViewInstance (this);
  1227. if (mbar != null) {
  1228. mbar.CleanUp ();
  1229. }
  1230. if (openMenu != null)
  1231. return;
  1232. selected = 0;
  1233. SetNeedsDisplay ();
  1234. previousFocused = SuperView == null ? Application.Current.Focused : SuperView.Focused;
  1235. OpenMenu (selected);
  1236. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current) && !CloseMenu (false)) {
  1237. return;
  1238. }
  1239. if (!openCurrentMenu.CheckSubMenu ())
  1240. return;
  1241. Application.GrabMouse (this);
  1242. }
  1243. // Activates the menu, handles either first focus, or activating an entry when it was already active
  1244. // For mouse events.
  1245. internal void Activate (int idx, int sIdx = -1, MenuBarItem subMenu = null)
  1246. {
  1247. selected = idx;
  1248. selectedSub = sIdx;
  1249. if (openMenu == null)
  1250. previousFocused = SuperView == null ? Application.Current.Focused : SuperView.Focused;
  1251. OpenMenu (idx, sIdx, subMenu);
  1252. SetNeedsDisplay ();
  1253. }
  1254. internal bool SelectEnabledItem (IEnumerable<MenuItem> chldren, int current, out int newCurrent, bool forward = true)
  1255. {
  1256. if (chldren == null) {
  1257. newCurrent = -1;
  1258. return true;
  1259. }
  1260. IEnumerable<MenuItem> childrens;
  1261. if (forward) {
  1262. childrens = chldren;
  1263. } else {
  1264. childrens = chldren.Reverse ();
  1265. }
  1266. int count;
  1267. if (forward) {
  1268. count = -1;
  1269. } else {
  1270. count = childrens.Count ();
  1271. }
  1272. foreach (var child in childrens) {
  1273. if (forward) {
  1274. if (++count < current) {
  1275. continue;
  1276. }
  1277. } else {
  1278. if (--count > current) {
  1279. continue;
  1280. }
  1281. }
  1282. if (child == null || !child.IsEnabled ()) {
  1283. if (forward) {
  1284. current++;
  1285. } else {
  1286. current--;
  1287. }
  1288. } else {
  1289. newCurrent = current;
  1290. return true;
  1291. }
  1292. }
  1293. newCurrent = -1;
  1294. return false;
  1295. }
  1296. /// <summary>
  1297. /// Closes the Menu programmatically if open and not canceled (as though F9 were pressed).
  1298. /// </summary>
  1299. public bool CloseMenu (bool ignoreUseSubMenusSingleFrame = false)
  1300. {
  1301. return CloseMenu (false, false, ignoreUseSubMenusSingleFrame);
  1302. }
  1303. bool reopen;
  1304. internal bool CloseMenu (bool reopen = false, bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  1305. {
  1306. var mbi = isSubMenu ? openCurrentMenu.barItems : openMenu?.barItems;
  1307. if (UseSubMenusSingleFrame && mbi != null &&
  1308. !ignoreUseSubMenusSingleFrame && mbi.Parent != null) {
  1309. return false;
  1310. }
  1311. isMenuClosing = true;
  1312. this.reopen = reopen;
  1313. var args = OnMenuClosing (mbi, reopen, isSubMenu);
  1314. if (args.Cancel) {
  1315. isMenuClosing = false;
  1316. if (args.CurrentMenu.Parent != null)
  1317. openMenu.current = ((MenuBarItem)args.CurrentMenu.Parent).Children.IndexOf (args.CurrentMenu);
  1318. return false;
  1319. }
  1320. switch (isSubMenu) {
  1321. case false:
  1322. if (openMenu != null) {
  1323. if (SuperView == null) {
  1324. Application.Current.Remove (openMenu);
  1325. } else {
  1326. SuperView?.Remove (openMenu);
  1327. }
  1328. }
  1329. SetNeedsDisplay ();
  1330. if (previousFocused != null && previousFocused is Menu && openMenu != null && previousFocused.ToString () != openCurrentMenu.ToString ())
  1331. previousFocused.SetFocus ();
  1332. openMenu?.Dispose ();
  1333. openMenu = null;
  1334. if (lastFocused is Menu || lastFocused is MenuBar) {
  1335. lastFocused = null;
  1336. }
  1337. LastFocused = lastFocused;
  1338. lastFocused = null;
  1339. if (LastFocused != null && LastFocused.CanFocus) {
  1340. if (!reopen) {
  1341. selected = -1;
  1342. }
  1343. LastFocused.SetFocus ();
  1344. } else if (LastFocused == null && !IsMenuOpen) {
  1345. Application.Current?.FocusFirst ();
  1346. } else {
  1347. SetFocus ();
  1348. PositionCursor ();
  1349. }
  1350. IsMenuOpen = false;
  1351. break;
  1352. case true:
  1353. selectedSub = -1;
  1354. SetNeedsDisplay ();
  1355. RemoveAllOpensSubMenus ();
  1356. openCurrentMenu.previousSubFocused.SetFocus ();
  1357. openSubMenu = null;
  1358. IsMenuOpen = true;
  1359. break;
  1360. }
  1361. this.reopen = false;
  1362. isMenuClosing = false;
  1363. return true;
  1364. }
  1365. void RemoveSubMenu (int index, bool ignoreUseSubMenusSingleFrame = false)
  1366. {
  1367. if (openSubMenu == null || (UseSubMenusSingleFrame
  1368. && !ignoreUseSubMenusSingleFrame && openSubMenu.Count == 0))
  1369. return;
  1370. for (int i = openSubMenu.Count - 1; i > index; i--) {
  1371. isMenuClosing = true;
  1372. Menu menu;
  1373. if (openSubMenu.Count - 1 > 0)
  1374. menu = openSubMenu [i - 1];
  1375. else
  1376. menu = openMenu;
  1377. if (!menu.Visible)
  1378. menu.Visible = true;
  1379. openCurrentMenu = menu;
  1380. openCurrentMenu.SetFocus ();
  1381. if (openSubMenu != null) {
  1382. menu = openSubMenu [i];
  1383. if (SuperView == null) {
  1384. Application.Current.Remove (menu);
  1385. } else {
  1386. SuperView.Remove (menu);
  1387. }
  1388. openSubMenu.Remove (menu);
  1389. menu.Dispose ();
  1390. }
  1391. RemoveSubMenu (i, ignoreUseSubMenusSingleFrame);
  1392. }
  1393. if (openSubMenu.Count > 0)
  1394. openCurrentMenu = openSubMenu.Last ();
  1395. isMenuClosing = false;
  1396. }
  1397. internal void RemoveAllOpensSubMenus ()
  1398. {
  1399. if (openSubMenu != null) {
  1400. foreach (var item in openSubMenu) {
  1401. if (SuperView == null) {
  1402. Application.Current.Remove (item);
  1403. } else {
  1404. SuperView.Remove (item);
  1405. }
  1406. item.Dispose ();
  1407. }
  1408. }
  1409. }
  1410. internal void CloseAllMenus ()
  1411. {
  1412. if (!isMenuOpening && !isMenuClosing) {
  1413. if (openSubMenu != null && !CloseMenu (false, true))
  1414. return;
  1415. if (!CloseMenu (false))
  1416. return;
  1417. if (LastFocused != null && LastFocused != this)
  1418. selected = -1;
  1419. Application.UngrabMouse ();
  1420. }
  1421. IsMenuOpen = false;
  1422. openedByHotKey = false;
  1423. openedByAltKey = false;
  1424. OnMenuAllClosed ();
  1425. }
  1426. View FindDeepestMenu (View view, ref int count)
  1427. {
  1428. count = count > 0 ? count : 0;
  1429. foreach (var menu in view.Subviews) {
  1430. if (menu is Menu) {
  1431. count++;
  1432. return FindDeepestMenu ((Menu)menu, ref count);
  1433. }
  1434. }
  1435. return view;
  1436. }
  1437. internal void PreviousMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  1438. {
  1439. switch (isSubMenu) {
  1440. case false:
  1441. if (selected <= 0)
  1442. selected = Menus.Length - 1;
  1443. else
  1444. selected--;
  1445. if (selected > -1 && !CloseMenu (true, false, ignoreUseSubMenusSingleFrame))
  1446. return;
  1447. OpenMenu (selected);
  1448. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current, false)) {
  1449. openCurrentMenu.current = 0;
  1450. }
  1451. break;
  1452. case true:
  1453. if (selectedSub > -1) {
  1454. selectedSub--;
  1455. RemoveSubMenu (selectedSub, ignoreUseSubMenusSingleFrame);
  1456. SetNeedsDisplay ();
  1457. } else
  1458. PreviousMenu ();
  1459. break;
  1460. }
  1461. }
  1462. internal void NextMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  1463. {
  1464. switch (isSubMenu) {
  1465. case false:
  1466. if (selected == -1)
  1467. selected = 0;
  1468. else if (selected + 1 == Menus.Length)
  1469. selected = 0;
  1470. else
  1471. selected++;
  1472. if (selected > -1 && !CloseMenu (true, ignoreUseSubMenusSingleFrame))
  1473. return;
  1474. OpenMenu (selected);
  1475. SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current);
  1476. break;
  1477. case true:
  1478. if (UseKeysUpDownAsKeysLeftRight) {
  1479. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame)) {
  1480. NextMenu (false, ignoreUseSubMenusSingleFrame);
  1481. }
  1482. } else {
  1483. var subMenu = openCurrentMenu.current > -1 && openCurrentMenu.barItems.Children.Length > 0
  1484. ? openCurrentMenu.barItems.SubMenu (openCurrentMenu.barItems.Children [openCurrentMenu.current])
  1485. : null;
  1486. if ((selectedSub == -1 || openSubMenu == null || openSubMenu?.Count - 1 == selectedSub) && subMenu == null) {
  1487. if (openSubMenu != null && !CloseMenu (false, true))
  1488. return;
  1489. NextMenu (false, ignoreUseSubMenusSingleFrame);
  1490. } else if (subMenu != null || (openCurrentMenu.current > -1
  1491. && !openCurrentMenu.barItems.Children [openCurrentMenu.current].IsFromSubMenu)) {
  1492. selectedSub++;
  1493. openCurrentMenu.CheckSubMenu ();
  1494. } else {
  1495. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame)) {
  1496. NextMenu (false, ignoreUseSubMenusSingleFrame);
  1497. }
  1498. return;
  1499. }
  1500. SetNeedsDisplay ();
  1501. if (UseKeysUpDownAsKeysLeftRight)
  1502. openCurrentMenu.CheckSubMenu ();
  1503. }
  1504. break;
  1505. }
  1506. }
  1507. bool openedByHotKey;
  1508. internal bool FindAndOpenMenuByHotkey (KeyEvent kb)
  1509. {
  1510. //int pos = 0;
  1511. var c = ((uint)kb.Key & (uint)Key.CharMask);
  1512. for (int i = 0; i < Menus.Length; i++) {
  1513. // TODO: this code is duplicated, hotkey should be part of the MenuBarItem
  1514. var mi = Menus [i];
  1515. int p = mi.Title.IndexOf (MenuBar.HotKeySpecifier);
  1516. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1517. if (Char.ToUpperInvariant ((char)mi.Title [p + 1]) == c) {
  1518. ProcessMenu (i, mi);
  1519. return true;
  1520. } else if (mi.Children?.Length > 0) {
  1521. if (FindAndOpenChildrenMenuByHotkey (kb, mi.Children)) {
  1522. return true;
  1523. }
  1524. }
  1525. } else if (mi.Children?.Length > 0) {
  1526. if (FindAndOpenChildrenMenuByHotkey (kb, mi.Children)) {
  1527. return true;
  1528. }
  1529. }
  1530. }
  1531. return false;
  1532. }
  1533. bool FindAndOpenChildrenMenuByHotkey (KeyEvent kb, MenuItem [] children)
  1534. {
  1535. var c = ((uint)kb.Key & (uint)Key.CharMask);
  1536. for (int i = 0; i < children.Length; i++) {
  1537. var mi = children [i];
  1538. if (mi == null) {
  1539. continue;
  1540. }
  1541. int p = mi.Title.IndexOf (MenuBar.HotKeySpecifier);
  1542. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1543. if (Char.ToUpperInvariant ((char)mi.Title [p + 1]) == c) {
  1544. if (mi.IsEnabled ()) {
  1545. var action = mi.Action;
  1546. if (action != null) {
  1547. Run (action);
  1548. }
  1549. }
  1550. return true;
  1551. } else if (mi is MenuBarItem menuBarItem && menuBarItem?.Children.Length > 0) {
  1552. if (FindAndOpenChildrenMenuByHotkey (kb, menuBarItem.Children)) {
  1553. return true;
  1554. }
  1555. }
  1556. } else if (mi is MenuBarItem menuBarItem && menuBarItem?.Children.Length > 0) {
  1557. if (FindAndOpenChildrenMenuByHotkey (kb, menuBarItem.Children)) {
  1558. return true;
  1559. }
  1560. }
  1561. }
  1562. return false;
  1563. }
  1564. internal bool FindAndOpenMenuByShortcut (KeyEvent kb, MenuItem [] children = null)
  1565. {
  1566. if (children == null) {
  1567. children = Menus;
  1568. }
  1569. var key = kb.KeyValue;
  1570. var keys = ShortcutHelper.GetModifiersKey (kb);
  1571. key |= (int)keys;
  1572. for (int i = 0; i < children.Length; i++) {
  1573. var mi = children [i];
  1574. if (mi == null) {
  1575. continue;
  1576. }
  1577. if ((!(mi is MenuBarItem mbiTopLevel) || mbiTopLevel.IsTopLevel) && mi.Shortcut != Key.Null && mi.Shortcut == (Key)key) {
  1578. if (mi.IsEnabled ()) {
  1579. var action = mi.Action;
  1580. if (action != null) {
  1581. Run (action);
  1582. }
  1583. }
  1584. return true;
  1585. }
  1586. if (mi is MenuBarItem menuBarItem && menuBarItem.Children != null && !menuBarItem.IsTopLevel && FindAndOpenMenuByShortcut (kb, menuBarItem.Children)) {
  1587. return true;
  1588. }
  1589. }
  1590. return false;
  1591. }
  1592. private void ProcessMenu (int i, MenuBarItem mi)
  1593. {
  1594. if (selected < 0 && IsMenuOpen) {
  1595. return;
  1596. }
  1597. if (mi.IsTopLevel) {
  1598. var menu = new Menu (this, i, 0, mi);
  1599. menu.Run (mi.Action);
  1600. menu.Dispose ();
  1601. } else {
  1602. openedByHotKey = true;
  1603. Application.GrabMouse (this);
  1604. selected = i;
  1605. OpenMenu (i);
  1606. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current) && !CloseMenu (false)) {
  1607. return;
  1608. }
  1609. if (!openCurrentMenu.CheckSubMenu ())
  1610. return;
  1611. }
  1612. SetNeedsDisplay ();
  1613. }
  1614. ///<inheritdoc/>
  1615. public override bool ProcessHotKey (KeyEvent kb)
  1616. {
  1617. if (kb.Key == Key) {
  1618. if (Visible && !IsMenuOpen) {
  1619. OpenMenu ();
  1620. } else {
  1621. CloseAllMenus ();
  1622. }
  1623. return true;
  1624. }
  1625. // To ncurses simulate a AltMask key pressing Alt+Space because
  1626. // it can't detect an alone special key down was pressed.
  1627. if (kb.IsAlt && kb.Key == Key.AltMask && openMenu == null) {
  1628. OnKeyDown (kb);
  1629. OnKeyUp (kb);
  1630. return true;
  1631. } else if (kb.IsAlt && !kb.IsCtrl && !kb.IsShift) {
  1632. if (FindAndOpenMenuByHotkey (kb)) return true;
  1633. }
  1634. //var kc = kb.KeyValue;
  1635. return base.ProcessHotKey (kb);
  1636. }
  1637. ///<inheritdoc/>
  1638. public override bool ProcessKey (KeyEvent kb)
  1639. {
  1640. if (InvokeKeybindings (kb) == true)
  1641. return true;
  1642. var key = kb.KeyValue;
  1643. if ((key >= 'a' && key <= 'z') || (key >= 'A' && key <= 'Z') || (key >= '0' && key <= '9')) {
  1644. char c = Char.ToUpper ((char)key);
  1645. if (selected == -1 || Menus [selected].IsTopLevel)
  1646. return false;
  1647. foreach (var mi in Menus [selected].Children) {
  1648. if (mi == null)
  1649. continue;
  1650. int p = mi.Title.IndexOf (MenuBar.HotKeySpecifier);
  1651. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1652. if (mi.Title [p + 1] == c) {
  1653. Selected (mi);
  1654. return true;
  1655. }
  1656. }
  1657. }
  1658. }
  1659. return false;
  1660. }
  1661. void CloseMenuBar ()
  1662. {
  1663. if (!CloseMenu (false))
  1664. return;
  1665. if (openedByAltKey) {
  1666. openedByAltKey = false;
  1667. LastFocused?.SetFocus ();
  1668. }
  1669. SetNeedsDisplay ();
  1670. }
  1671. void MoveRight ()
  1672. {
  1673. selected = (selected + 1) % Menus.Length;
  1674. OpenMenu (selected);
  1675. SetNeedsDisplay ();
  1676. }
  1677. void MoveLeft ()
  1678. {
  1679. selected--;
  1680. if (selected < 0)
  1681. selected = Menus.Length - 1;
  1682. OpenMenu (selected);
  1683. SetNeedsDisplay ();
  1684. }
  1685. ///<inheritdoc/>
  1686. public override bool ProcessColdKey (KeyEvent kb)
  1687. {
  1688. return FindAndOpenMenuByShortcut (kb);
  1689. }
  1690. ///<inheritdoc/>
  1691. public override bool MouseEvent (MouseEvent me)
  1692. {
  1693. if (!handled && !HandleGrabView (me, this)) {
  1694. return false;
  1695. }
  1696. handled = false;
  1697. if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked || me.Flags == MouseFlags.Button1Clicked ||
  1698. (me.Flags == MouseFlags.ReportMousePosition && selected > -1) ||
  1699. (me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && selected > -1)) {
  1700. int pos = xOrigin;
  1701. int cx = me.X;
  1702. for (int i = 0; i < Menus.Length; i++) {
  1703. if (cx >= pos && cx < pos + leftPadding + Menus [i].TitleLength + Menus [i].Help.ConsoleWidth + rightPadding) {
  1704. if (me.Flags == MouseFlags.Button1Clicked) {
  1705. if (Menus [i].IsTopLevel) {
  1706. var menu = new Menu (this, i, 0, Menus [i]);
  1707. menu.Run (Menus [i].Action);
  1708. menu.Dispose ();
  1709. } else if (!IsMenuOpen) {
  1710. Activate (i);
  1711. }
  1712. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked) {
  1713. if (IsMenuOpen && !Menus [i].IsTopLevel) {
  1714. CloseAllMenus ();
  1715. } else if (!Menus [i].IsTopLevel) {
  1716. Activate (i);
  1717. }
  1718. } else if (selected != i && selected > -1 && (me.Flags == MouseFlags.ReportMousePosition ||
  1719. me.Flags == MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)) {
  1720. if (IsMenuOpen) {
  1721. if (!CloseMenu (true, false)) {
  1722. return true;
  1723. }
  1724. Activate (i);
  1725. }
  1726. } else {
  1727. if (IsMenuOpen)
  1728. Activate (i);
  1729. }
  1730. return true;
  1731. }
  1732. pos += leftPadding + Menus [i].TitleLength + rightPadding;
  1733. }
  1734. }
  1735. return false;
  1736. }
  1737. internal bool handled;
  1738. internal bool isContextMenuLoading;
  1739. internal bool HandleGrabView (MouseEvent me, View current)
  1740. {
  1741. if (Application.MouseGrabView != null) {
  1742. if (me.View is MenuBar || me.View is Menu) {
  1743. var mbar = GetMouseGrabViewInstance (me.View);
  1744. if (mbar != null) {
  1745. if (me.Flags == MouseFlags.Button1Clicked) {
  1746. mbar.CleanUp ();
  1747. Application.GrabMouse (me.View);
  1748. } else {
  1749. handled = false;
  1750. return false;
  1751. }
  1752. }
  1753. if (me.View != current) {
  1754. Application.UngrabMouse ();
  1755. var v = me.View;
  1756. Application.GrabMouse (v);
  1757. MouseEvent nme;
  1758. if (me.Y > -1) {
  1759. var newxy = v.ScreenToView (me.X, me.Y);
  1760. nme = new MouseEvent () {
  1761. X = newxy.X,
  1762. Y = newxy.Y,
  1763. Flags = me.Flags,
  1764. OfX = me.X - newxy.X,
  1765. OfY = me.Y - newxy.Y,
  1766. View = v
  1767. };
  1768. } else {
  1769. nme = new MouseEvent () {
  1770. X = me.X + current.Frame.X,
  1771. Y = 0,
  1772. Flags = me.Flags,
  1773. View = v
  1774. };
  1775. }
  1776. v.MouseEvent (nme);
  1777. return false;
  1778. }
  1779. } else if (!isContextMenuLoading && !(me.View is MenuBar || me.View is Menu)
  1780. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  1781. Application.UngrabMouse ();
  1782. if (IsMenuOpen)
  1783. CloseAllMenus ();
  1784. handled = false;
  1785. return false;
  1786. } else {
  1787. handled = false;
  1788. isContextMenuLoading = false;
  1789. return false;
  1790. }
  1791. } else if (!IsMenuOpen && (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked
  1792. || me.Flags == MouseFlags.Button1TripleClicked || me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))) {
  1793. Application.GrabMouse (current);
  1794. } else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu)) {
  1795. Application.GrabMouse (me.View);
  1796. } else {
  1797. handled = false;
  1798. return false;
  1799. }
  1800. handled = true;
  1801. return true;
  1802. }
  1803. MenuBar GetMouseGrabViewInstance (View view)
  1804. {
  1805. if (view == null || Application.MouseGrabView == null) {
  1806. return null;
  1807. }
  1808. MenuBar hostView = null;
  1809. if (view is MenuBar) {
  1810. hostView = (MenuBar)view;
  1811. } else if (view is Menu) {
  1812. hostView = ((Menu)view).host;
  1813. }
  1814. var grabView = Application.MouseGrabView;
  1815. MenuBar hostGrabView = null;
  1816. if (grabView is MenuBar) {
  1817. hostGrabView = (MenuBar)grabView;
  1818. } else if (grabView is Menu) {
  1819. hostGrabView = ((Menu)grabView).host;
  1820. }
  1821. return hostView != hostGrabView ? hostGrabView : null;
  1822. }
  1823. ///<inheritdoc/>
  1824. public override bool OnEnter (View view)
  1825. {
  1826. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  1827. return base.OnEnter (view);
  1828. }
  1829. }
  1830. /// <summary>
  1831. /// An <see cref="EventArgs"/> which allows passing a cancelable menu opening event or replacing with a new <see cref="MenuBarItem"/>.
  1832. /// </summary>
  1833. public class MenuOpeningEventArgs : EventArgs {
  1834. /// <summary>
  1835. /// The current <see cref="MenuBarItem"/> parent.
  1836. /// </summary>
  1837. public MenuBarItem CurrentMenu { get; }
  1838. /// <summary>
  1839. /// The new <see cref="MenuBarItem"/> to be replaced.
  1840. /// </summary>
  1841. public MenuBarItem NewMenuBarItem { get; set; }
  1842. /// <summary>
  1843. /// Flag that allows the cancellation of the event. If set to <see langword="true"/> in the
  1844. /// event handler, the event will be canceled.
  1845. /// </summary>
  1846. public bool Cancel { get; set; }
  1847. /// <summary>
  1848. /// Initializes a new instance of <see cref="MenuOpeningEventArgs"/>.
  1849. /// </summary>
  1850. /// <param name="currentMenu">The current <see cref="MenuBarItem"/> parent.</param>
  1851. public MenuOpeningEventArgs (MenuBarItem currentMenu)
  1852. {
  1853. CurrentMenu = currentMenu;
  1854. }
  1855. }
  1856. /// <summary>
  1857. /// An <see cref="EventArgs"/> which allows passing a cancelable menu closing event.
  1858. /// </summary>
  1859. public class MenuClosingEventArgs : EventArgs {
  1860. /// <summary>
  1861. /// The current <see cref="MenuBarItem"/> parent.
  1862. /// </summary>
  1863. public MenuBarItem CurrentMenu { get; }
  1864. /// <summary>
  1865. /// Indicates whether the current menu will reopen.
  1866. /// </summary>
  1867. public bool Reopen { get; }
  1868. /// <summary>
  1869. /// Indicates whether the current menu is a sub-menu.
  1870. /// </summary>
  1871. public bool IsSubMenu { get; }
  1872. /// <summary>
  1873. /// Flag that allows the cancellation of the event. If set to <see langword="true"/> in the
  1874. /// event handler, the event will be canceled.
  1875. /// </summary>
  1876. public bool Cancel { get; set; }
  1877. /// <summary>
  1878. /// Initializes a new instance of <see cref="MenuClosingEventArgs"/>.
  1879. /// </summary>
  1880. /// <param name="currentMenu">The current <see cref="MenuBarItem"/> parent.</param>
  1881. /// <param name="reopen">Whether the current menu will reopen.</param>
  1882. /// <param name="isSubMenu">Indicates whether it is a sub-menu.</param>
  1883. public MenuClosingEventArgs (MenuBarItem currentMenu, bool reopen, bool isSubMenu)
  1884. {
  1885. CurrentMenu = currentMenu;
  1886. Reopen = reopen;
  1887. IsSubMenu = isSubMenu;
  1888. }
  1889. }
  1890. }