Menu.cs 59 KB

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