Menu.cs 61 KB

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