2
0

Menu.cs 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071
  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 Action<MenuItem> 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. if (openCurrentMenu.barItems.Children != null && openCurrentMenu.barItems.Children.Length > 0
  1133. && openCurrentMenu?.current > -1) {
  1134. mi = openCurrentMenu.barItems.Children [openCurrentMenu.current];
  1135. } else if (openCurrentMenu.barItems.IsTopLevel) {
  1136. mi = openCurrentMenu.barItems;
  1137. } else {
  1138. mi = openMenu.barItems.Children [openMenu.current];
  1139. }
  1140. MenuOpened?.Invoke (mi);
  1141. }
  1142. /// <summary>
  1143. /// Virtual method that will invoke the <see cref="MenuClosing"/>.
  1144. /// </summary>
  1145. /// <param name="currentMenu">The current menu to be closed.</param>
  1146. /// <param name="reopen">Whether the current menu will be reopen.</param>
  1147. /// <param name="isSubMenu">Whether is a sub-menu or not.</param>
  1148. public virtual MenuClosingEventArgs OnMenuClosing (MenuBarItem currentMenu, bool reopen, bool isSubMenu)
  1149. {
  1150. var ev = new MenuClosingEventArgs (currentMenu, reopen, isSubMenu);
  1151. MenuClosing?.Invoke (this, ev);
  1152. return ev;
  1153. }
  1154. /// <summary>
  1155. /// Virtual method that will invoke the <see cref="MenuAllClosed"/>.
  1156. /// </summary>
  1157. public virtual void OnMenuAllClosed ()
  1158. {
  1159. MenuAllClosed?.Invoke (this, EventArgs.Empty);
  1160. }
  1161. View lastFocused;
  1162. /// <summary>
  1163. /// Gets the view that was last focused before opening the menu.
  1164. /// </summary>
  1165. public View LastFocused { get; private set; }
  1166. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem subMenu = null)
  1167. {
  1168. isMenuOpening = true;
  1169. var newMenu = OnMenuOpening (Menus [index]);
  1170. if (newMenu.Cancel) {
  1171. isMenuOpening = false;
  1172. return;
  1173. }
  1174. if (newMenu.NewMenuBarItem != null) {
  1175. Menus [index] = newMenu.NewMenuBarItem;
  1176. }
  1177. int pos = 0;
  1178. switch (subMenu) {
  1179. case null:
  1180. // Open a submenu below a MenuBar
  1181. lastFocused = lastFocused ?? (SuperView == null ? Application.Current.MostFocused : SuperView.MostFocused);
  1182. if (openSubMenu != null && !CloseMenu (false, true))
  1183. return;
  1184. if (openMenu != null) {
  1185. if (SuperView == null) {
  1186. Application.Current.Remove (openMenu);
  1187. } else {
  1188. SuperView.Remove (openMenu);
  1189. }
  1190. openMenu.Dispose ();
  1191. }
  1192. // This positions the submenu horizontally aligned with the first character of the
  1193. // menu it belongs to's text
  1194. for (int i = 0; i < index; i++)
  1195. pos += Menus [i].TitleLength + (Menus [i].Help.ConsoleWidth > 0 ? Menus [i].Help.ConsoleWidth + 2 : 0) + leftPadding + rightPadding;
  1196. openMenu = new Menu (this, Frame.X + pos, Frame.Y + 1, Menus [index]);
  1197. openCurrentMenu = openMenu;
  1198. openCurrentMenu.previousSubFocused = openMenu;
  1199. if (SuperView == null) {
  1200. Application.Current.Add (openMenu);
  1201. } else {
  1202. SuperView.Add (openMenu);
  1203. }
  1204. openMenu.SetFocus ();
  1205. break;
  1206. default:
  1207. // Opens a submenu next to another submenu (openSubMenu)
  1208. if (openSubMenu == null)
  1209. openSubMenu = new List<Menu> ();
  1210. if (sIndex > -1) {
  1211. RemoveSubMenu (sIndex);
  1212. } else {
  1213. var last = openSubMenu.Count > 0 ? openSubMenu.Last () : openMenu;
  1214. if (!UseSubMenusSingleFrame) {
  1215. openCurrentMenu = new Menu (this, last.Frame.Left + last.Frame.Width, last.Frame.Top + 1 + last.current, subMenu, last);
  1216. } else {
  1217. var first = openSubMenu.Count > 0 ? openSubMenu.First () : openMenu;
  1218. var mbi = new MenuItem [2 + subMenu.Children.Length];
  1219. mbi [0] = new MenuItem () { Title = subMenu.Title, Parent = subMenu };
  1220. mbi [1] = null;
  1221. for (int j = 0; j < subMenu.Children.Length; j++) {
  1222. mbi [j + 2] = subMenu.Children [j];
  1223. }
  1224. var newSubMenu = new MenuBarItem (mbi);
  1225. openCurrentMenu = new Menu (this, first.Frame.Left, first.Frame.Top, newSubMenu);
  1226. last.Visible = false;
  1227. Application.GrabMouse (openCurrentMenu);
  1228. }
  1229. openCurrentMenu.previousSubFocused = last.previousSubFocused;
  1230. openSubMenu.Add (openCurrentMenu);
  1231. if (SuperView == null) {
  1232. Application.Current.Add (openCurrentMenu);
  1233. } else {
  1234. SuperView.Add (openCurrentMenu);
  1235. }
  1236. }
  1237. selectedSub = openSubMenu.Count - 1;
  1238. if (selectedSub > -1 && SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current)) {
  1239. openCurrentMenu.SetFocus ();
  1240. }
  1241. break;
  1242. }
  1243. isMenuOpening = false;
  1244. IsMenuOpen = true;
  1245. }
  1246. /// <summary>
  1247. /// Opens the Menu programatically, as though the F9 key were pressed.
  1248. /// </summary>
  1249. public void OpenMenu ()
  1250. {
  1251. var mbar = GetMouseGrabViewInstance (this);
  1252. if (mbar != null) {
  1253. mbar.CleanUp ();
  1254. }
  1255. if (openMenu != null)
  1256. return;
  1257. selected = 0;
  1258. SetNeedsDisplay ();
  1259. previousFocused = SuperView == null ? Application.Current.Focused : SuperView.Focused;
  1260. OpenMenu (selected);
  1261. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current) && !CloseMenu (false)) {
  1262. return;
  1263. }
  1264. if (!openCurrentMenu.CheckSubMenu ())
  1265. return;
  1266. Application.GrabMouse (this);
  1267. }
  1268. // Activates the menu, handles either first focus, or activating an entry when it was already active
  1269. // For mouse events.
  1270. internal void Activate (int idx, int sIdx = -1, MenuBarItem subMenu = null)
  1271. {
  1272. selected = idx;
  1273. selectedSub = sIdx;
  1274. if (openMenu == null)
  1275. previousFocused = SuperView == null ? Application.Current.Focused : SuperView.Focused;
  1276. OpenMenu (idx, sIdx, subMenu);
  1277. SetNeedsDisplay ();
  1278. }
  1279. internal bool SelectEnabledItem (IEnumerable<MenuItem> chldren, int current, out int newCurrent, bool forward = true)
  1280. {
  1281. if (chldren == null) {
  1282. newCurrent = -1;
  1283. return true;
  1284. }
  1285. IEnumerable<MenuItem> childrens;
  1286. if (forward) {
  1287. childrens = chldren;
  1288. } else {
  1289. childrens = chldren.Reverse ();
  1290. }
  1291. int count;
  1292. if (forward) {
  1293. count = -1;
  1294. } else {
  1295. count = childrens.Count ();
  1296. }
  1297. foreach (var child in childrens) {
  1298. if (forward) {
  1299. if (++count < current) {
  1300. continue;
  1301. }
  1302. } else {
  1303. if (--count > current) {
  1304. continue;
  1305. }
  1306. }
  1307. if (child == null || !child.IsEnabled ()) {
  1308. if (forward) {
  1309. current++;
  1310. } else {
  1311. current--;
  1312. }
  1313. } else {
  1314. newCurrent = current;
  1315. return true;
  1316. }
  1317. }
  1318. newCurrent = -1;
  1319. return false;
  1320. }
  1321. /// <summary>
  1322. /// Closes the Menu programmatically if open and not canceled (as though F9 were pressed).
  1323. /// </summary>
  1324. public bool CloseMenu (bool ignoreUseSubMenusSingleFrame = false)
  1325. {
  1326. return CloseMenu (false, false, ignoreUseSubMenusSingleFrame);
  1327. }
  1328. bool reopen;
  1329. internal bool CloseMenu (bool reopen = false, bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  1330. {
  1331. var mbi = isSubMenu ? openCurrentMenu.barItems : openMenu?.barItems;
  1332. if (UseSubMenusSingleFrame && mbi != null &&
  1333. !ignoreUseSubMenusSingleFrame && mbi.Parent != null) {
  1334. return false;
  1335. }
  1336. isMenuClosing = true;
  1337. this.reopen = reopen;
  1338. var args = OnMenuClosing (mbi, reopen, isSubMenu);
  1339. if (args.Cancel) {
  1340. isMenuClosing = false;
  1341. if (args.CurrentMenu.Parent != null)
  1342. openMenu.current = ((MenuBarItem)args.CurrentMenu.Parent).Children.IndexOf (args.CurrentMenu);
  1343. return false;
  1344. }
  1345. switch (isSubMenu) {
  1346. case false:
  1347. if (openMenu != null) {
  1348. if (SuperView == null) {
  1349. Application.Current.Remove (openMenu);
  1350. } else {
  1351. SuperView?.Remove (openMenu);
  1352. }
  1353. }
  1354. SetNeedsDisplay ();
  1355. if (previousFocused != null && previousFocused is Menu && openMenu != null && previousFocused.ToString () != openCurrentMenu.ToString ())
  1356. previousFocused.SetFocus ();
  1357. openMenu?.Dispose ();
  1358. openMenu = null;
  1359. if (lastFocused is Menu || lastFocused is MenuBar) {
  1360. lastFocused = null;
  1361. }
  1362. LastFocused = lastFocused;
  1363. lastFocused = null;
  1364. if (LastFocused != null && LastFocused.CanFocus) {
  1365. if (!reopen) {
  1366. selected = -1;
  1367. }
  1368. LastFocused.SetFocus ();
  1369. } else {
  1370. SetFocus ();
  1371. PositionCursor ();
  1372. }
  1373. IsMenuOpen = false;
  1374. break;
  1375. case true:
  1376. selectedSub = -1;
  1377. SetNeedsDisplay ();
  1378. RemoveAllOpensSubMenus ();
  1379. openCurrentMenu.previousSubFocused.SetFocus ();
  1380. openSubMenu = null;
  1381. IsMenuOpen = true;
  1382. break;
  1383. }
  1384. this.reopen = false;
  1385. isMenuClosing = false;
  1386. return true;
  1387. }
  1388. void RemoveSubMenu (int index, bool ignoreUseSubMenusSingleFrame = false)
  1389. {
  1390. if (openSubMenu == null || (UseSubMenusSingleFrame
  1391. && !ignoreUseSubMenusSingleFrame && openSubMenu.Count == 0))
  1392. return;
  1393. for (int i = openSubMenu.Count - 1; i > index; i--) {
  1394. isMenuClosing = true;
  1395. Menu menu;
  1396. if (openSubMenu.Count - 1 > 0)
  1397. menu = openSubMenu [i - 1];
  1398. else
  1399. menu = openMenu;
  1400. if (!menu.Visible)
  1401. menu.Visible = true;
  1402. openCurrentMenu = menu;
  1403. openCurrentMenu.SetFocus ();
  1404. if (openSubMenu != null) {
  1405. menu = openSubMenu [i];
  1406. if (SuperView == null) {
  1407. Application.Current.Remove (menu);
  1408. } else {
  1409. SuperView.Remove (menu);
  1410. }
  1411. openSubMenu.Remove (menu);
  1412. menu.Dispose ();
  1413. }
  1414. RemoveSubMenu (i, ignoreUseSubMenusSingleFrame);
  1415. }
  1416. if (openSubMenu.Count > 0)
  1417. openCurrentMenu = openSubMenu.Last ();
  1418. isMenuClosing = false;
  1419. }
  1420. internal void RemoveAllOpensSubMenus ()
  1421. {
  1422. if (openSubMenu != null) {
  1423. foreach (var item in openSubMenu) {
  1424. if (SuperView == null) {
  1425. Application.Current.Remove (item);
  1426. } else {
  1427. SuperView.Remove (item);
  1428. }
  1429. item.Dispose ();
  1430. }
  1431. }
  1432. }
  1433. internal void CloseAllMenus ()
  1434. {
  1435. if (!isMenuOpening && !isMenuClosing) {
  1436. if (openSubMenu != null && !CloseMenu (false, true))
  1437. return;
  1438. if (!CloseMenu (false))
  1439. return;
  1440. if (LastFocused != null && LastFocused != this)
  1441. selected = -1;
  1442. Application.UngrabMouse ();
  1443. }
  1444. IsMenuOpen = false;
  1445. openedByHotKey = false;
  1446. openedByAltKey = false;
  1447. OnMenuAllClosed ();
  1448. }
  1449. View FindDeepestMenu (View view, ref int count)
  1450. {
  1451. count = count > 0 ? count : 0;
  1452. foreach (var menu in view.Subviews) {
  1453. if (menu is Menu) {
  1454. count++;
  1455. return FindDeepestMenu ((Menu)menu, ref count);
  1456. }
  1457. }
  1458. return view;
  1459. }
  1460. internal void PreviousMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  1461. {
  1462. switch (isSubMenu) {
  1463. case false:
  1464. if (selected <= 0)
  1465. selected = Menus.Length - 1;
  1466. else
  1467. selected--;
  1468. if (selected > -1 && !CloseMenu (true, false, ignoreUseSubMenusSingleFrame))
  1469. return;
  1470. OpenMenu (selected);
  1471. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current, false)) {
  1472. openCurrentMenu.current = 0;
  1473. }
  1474. break;
  1475. case true:
  1476. if (selectedSub > -1) {
  1477. selectedSub--;
  1478. RemoveSubMenu (selectedSub, ignoreUseSubMenusSingleFrame);
  1479. SetNeedsDisplay ();
  1480. } else
  1481. PreviousMenu ();
  1482. break;
  1483. }
  1484. }
  1485. internal void NextMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  1486. {
  1487. switch (isSubMenu) {
  1488. case false:
  1489. if (selected == -1)
  1490. selected = 0;
  1491. else if (selected + 1 == Menus.Length)
  1492. selected = 0;
  1493. else
  1494. selected++;
  1495. if (selected > -1 && !CloseMenu (true, ignoreUseSubMenusSingleFrame))
  1496. return;
  1497. OpenMenu (selected);
  1498. SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current);
  1499. break;
  1500. case true:
  1501. if (UseKeysUpDownAsKeysLeftRight) {
  1502. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame)) {
  1503. NextMenu (false, ignoreUseSubMenusSingleFrame);
  1504. }
  1505. } else {
  1506. var subMenu = openCurrentMenu.current > -1 && openCurrentMenu.barItems.Children.Length > 0
  1507. ? openCurrentMenu.barItems.SubMenu (openCurrentMenu.barItems.Children [openCurrentMenu.current])
  1508. : null;
  1509. if ((selectedSub == -1 || openSubMenu == null || openSubMenu?.Count - 1 == selectedSub) && subMenu == null) {
  1510. if (openSubMenu != null && !CloseMenu (false, true))
  1511. return;
  1512. NextMenu (false, ignoreUseSubMenusSingleFrame);
  1513. } else if (subMenu != null || (openCurrentMenu.current > -1
  1514. && !openCurrentMenu.barItems.Children [openCurrentMenu.current].IsFromSubMenu)) {
  1515. selectedSub++;
  1516. openCurrentMenu.CheckSubMenu ();
  1517. } else {
  1518. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame)) {
  1519. NextMenu (false, ignoreUseSubMenusSingleFrame);
  1520. }
  1521. return;
  1522. }
  1523. SetNeedsDisplay ();
  1524. if (UseKeysUpDownAsKeysLeftRight)
  1525. openCurrentMenu.CheckSubMenu ();
  1526. }
  1527. break;
  1528. }
  1529. }
  1530. bool openedByHotKey;
  1531. internal bool FindAndOpenMenuByHotkey (KeyEvent kb)
  1532. {
  1533. //int pos = 0;
  1534. var c = ((uint)kb.Key & (uint)Key.CharMask);
  1535. for (int i = 0; i < Menus.Length; i++) {
  1536. // TODO: this code is duplicated, hotkey should be part of the MenuBarItem
  1537. var mi = Menus [i];
  1538. int p = mi.Title.IndexOf (MenuBar.HotKeySpecifier);
  1539. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1540. if (Char.ToUpperInvariant ((char)mi.Title [p + 1]) == c) {
  1541. ProcessMenu (i, mi);
  1542. return true;
  1543. }
  1544. }
  1545. }
  1546. return false;
  1547. }
  1548. internal bool FindAndOpenMenuByShortcut (KeyEvent kb, MenuItem [] children = null)
  1549. {
  1550. if (children == null) {
  1551. children = Menus;
  1552. }
  1553. var key = kb.KeyValue;
  1554. var keys = ShortcutHelper.GetModifiersKey (kb);
  1555. key |= (int)keys;
  1556. for (int i = 0; i < children.Length; i++) {
  1557. var mi = children [i];
  1558. if (mi == null) {
  1559. continue;
  1560. }
  1561. if ((!(mi is MenuBarItem mbiTopLevel) || mbiTopLevel.IsTopLevel) && mi.Shortcut != Key.Null && mi.Shortcut == (Key)key) {
  1562. var action = mi.Action;
  1563. if (action != null) {
  1564. Application.MainLoop.AddIdle (() => {
  1565. action ();
  1566. return false;
  1567. });
  1568. }
  1569. return true;
  1570. }
  1571. if (mi is MenuBarItem menuBarItem && !menuBarItem.IsTopLevel && FindAndOpenMenuByShortcut (kb, menuBarItem.Children)) {
  1572. return true;
  1573. }
  1574. }
  1575. return false;
  1576. }
  1577. private void ProcessMenu (int i, MenuBarItem mi)
  1578. {
  1579. if (selected < 0 && IsMenuOpen) {
  1580. return;
  1581. }
  1582. if (mi.IsTopLevel) {
  1583. var menu = new Menu (this, i, 0, mi);
  1584. menu.Run (mi.Action);
  1585. menu.Dispose ();
  1586. } else {
  1587. openedByHotKey = true;
  1588. Application.GrabMouse (this);
  1589. selected = i;
  1590. OpenMenu (i);
  1591. if (!SelectEnabledItem (openCurrentMenu.barItems.Children, openCurrentMenu.current, out openCurrentMenu.current) && !CloseMenu (false)) {
  1592. return;
  1593. }
  1594. if (!openCurrentMenu.CheckSubMenu ())
  1595. return;
  1596. }
  1597. SetNeedsDisplay ();
  1598. }
  1599. ///<inheritdoc/>
  1600. public override bool ProcessHotKey (KeyEvent kb)
  1601. {
  1602. if (kb.Key == Key) {
  1603. if (!IsMenuOpen)
  1604. OpenMenu ();
  1605. else
  1606. CloseAllMenus ();
  1607. return true;
  1608. }
  1609. // To ncurses simulate a AltMask key pressing Alt+Space because
  1610. // it can't detect an alone special key down was pressed.
  1611. if (kb.IsAlt && kb.Key == Key.AltMask && openMenu == null) {
  1612. OnKeyDown (kb);
  1613. OnKeyUp (kb);
  1614. return true;
  1615. } else if (kb.IsAlt && !kb.IsCtrl && !kb.IsShift) {
  1616. if (FindAndOpenMenuByHotkey (kb)) return true;
  1617. }
  1618. //var kc = kb.KeyValue;
  1619. return base.ProcessHotKey (kb);
  1620. }
  1621. ///<inheritdoc/>
  1622. public override bool ProcessKey (KeyEvent kb)
  1623. {
  1624. if (InvokeKeybindings (kb) == true)
  1625. return true;
  1626. var key = kb.KeyValue;
  1627. if ((key >= 'a' && key <= 'z') || (key >= 'A' && key <= 'Z') || (key >= '0' && key <= '9')) {
  1628. char c = Char.ToUpper ((char)key);
  1629. if (selected == -1 || Menus [selected].IsTopLevel)
  1630. return false;
  1631. foreach (var mi in Menus [selected].Children) {
  1632. if (mi == null)
  1633. continue;
  1634. int p = mi.Title.IndexOf (MenuBar.HotKeySpecifier);
  1635. if (p != -1 && p + 1 < mi.Title.RuneCount) {
  1636. if (mi.Title [p + 1] == c) {
  1637. Selected (mi);
  1638. return true;
  1639. }
  1640. }
  1641. }
  1642. }
  1643. return false;
  1644. }
  1645. void CloseMenuBar ()
  1646. {
  1647. if (!CloseMenu (false))
  1648. return;
  1649. if (openedByAltKey) {
  1650. openedByAltKey = false;
  1651. LastFocused?.SetFocus ();
  1652. }
  1653. SetNeedsDisplay ();
  1654. }
  1655. void MoveRight ()
  1656. {
  1657. selected = (selected + 1) % Menus.Length;
  1658. OpenMenu (selected);
  1659. SetNeedsDisplay ();
  1660. }
  1661. void MoveLeft ()
  1662. {
  1663. selected--;
  1664. if (selected < 0)
  1665. selected = Menus.Length - 1;
  1666. OpenMenu (selected);
  1667. SetNeedsDisplay ();
  1668. }
  1669. ///<inheritdoc/>
  1670. public override bool ProcessColdKey (KeyEvent kb)
  1671. {
  1672. return FindAndOpenMenuByShortcut (kb);
  1673. }
  1674. ///<inheritdoc/>
  1675. public override bool MouseEvent (MouseEvent me)
  1676. {
  1677. if (!handled && !HandleGrabView (me, this)) {
  1678. return false;
  1679. }
  1680. handled = false;
  1681. if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked || me.Flags == MouseFlags.Button1Clicked ||
  1682. (me.Flags == MouseFlags.ReportMousePosition && selected > -1) ||
  1683. (me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && selected > -1)) {
  1684. int pos = xOrigin;
  1685. int cx = me.X;
  1686. for (int i = 0; i < Menus.Length; i++) {
  1687. if (cx >= pos && cx < pos + leftPadding + Menus [i].TitleLength + Menus [i].Help.ConsoleWidth + rightPadding) {
  1688. if (me.Flags == MouseFlags.Button1Clicked) {
  1689. if (Menus [i].IsTopLevel) {
  1690. var menu = new Menu (this, i, 0, Menus [i]);
  1691. menu.Run (Menus [i].Action);
  1692. menu.Dispose ();
  1693. } else if (!IsMenuOpen) {
  1694. Activate (i);
  1695. }
  1696. } else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked || me.Flags == MouseFlags.Button1TripleClicked) {
  1697. if (IsMenuOpen && !Menus [i].IsTopLevel) {
  1698. CloseAllMenus ();
  1699. } else if (!Menus [i].IsTopLevel) {
  1700. Activate (i);
  1701. }
  1702. } else if (selected != i && selected > -1 && (me.Flags == MouseFlags.ReportMousePosition ||
  1703. me.Flags == MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)) {
  1704. if (IsMenuOpen) {
  1705. if (!CloseMenu (true, false)) {
  1706. return true;
  1707. }
  1708. Activate (i);
  1709. }
  1710. } else {
  1711. if (IsMenuOpen)
  1712. Activate (i);
  1713. }
  1714. return true;
  1715. }
  1716. pos += leftPadding + Menus [i].TitleLength + rightPadding;
  1717. }
  1718. }
  1719. return false;
  1720. }
  1721. internal bool handled;
  1722. internal bool isContextMenuLoading;
  1723. internal bool HandleGrabView (MouseEvent me, View current)
  1724. {
  1725. if (Application.MouseGrabView != null) {
  1726. if (me.View is MenuBar || me.View is Menu) {
  1727. var mbar = GetMouseGrabViewInstance (me.View);
  1728. if (mbar != null) {
  1729. if (me.Flags == MouseFlags.Button1Clicked) {
  1730. mbar.CleanUp ();
  1731. Application.GrabMouse (me.View);
  1732. } else {
  1733. handled = false;
  1734. return false;
  1735. }
  1736. }
  1737. if (me.View != current) {
  1738. Application.UngrabMouse ();
  1739. var v = me.View;
  1740. Application.GrabMouse (v);
  1741. MouseEvent nme;
  1742. if (me.Y > -1) {
  1743. var newxy = v.ScreenToView (me.X, me.Y);
  1744. nme = new MouseEvent () {
  1745. X = newxy.X,
  1746. Y = newxy.Y,
  1747. Flags = me.Flags,
  1748. OfX = me.X - newxy.X,
  1749. OfY = me.Y - newxy.Y,
  1750. View = v
  1751. };
  1752. } else {
  1753. nme = new MouseEvent () {
  1754. X = me.X + current.Frame.X,
  1755. Y = 0,
  1756. Flags = me.Flags,
  1757. View = v
  1758. };
  1759. }
  1760. v.MouseEvent (nme);
  1761. return false;
  1762. }
  1763. } else if (!isContextMenuLoading && !(me.View is MenuBar || me.View is Menu)
  1764. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  1765. Application.UngrabMouse ();
  1766. if (IsMenuOpen)
  1767. CloseAllMenus ();
  1768. handled = false;
  1769. return false;
  1770. } else {
  1771. handled = false;
  1772. isContextMenuLoading = false;
  1773. return false;
  1774. }
  1775. } else if (!IsMenuOpen && (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked
  1776. || me.Flags == MouseFlags.Button1TripleClicked || me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))) {
  1777. Application.GrabMouse (current);
  1778. } else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu)) {
  1779. Application.GrabMouse (me.View);
  1780. } else {
  1781. handled = false;
  1782. return false;
  1783. }
  1784. handled = true;
  1785. return true;
  1786. }
  1787. MenuBar GetMouseGrabViewInstance (View view)
  1788. {
  1789. if (view == null || Application.MouseGrabView == null) {
  1790. return null;
  1791. }
  1792. MenuBar hostView = null;
  1793. if (view is MenuBar) {
  1794. hostView = (MenuBar)view;
  1795. } else if (view is Menu) {
  1796. hostView = ((Menu)view).host;
  1797. }
  1798. var grabView = Application.MouseGrabView;
  1799. MenuBar hostGrabView = null;
  1800. if (grabView is MenuBar) {
  1801. hostGrabView = (MenuBar)grabView;
  1802. } else if (grabView is Menu) {
  1803. hostGrabView = ((Menu)grabView).host;
  1804. }
  1805. return hostView != hostGrabView ? hostGrabView : null;
  1806. }
  1807. ///<inheritdoc/>
  1808. public override bool OnEnter (View view)
  1809. {
  1810. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  1811. return base.OnEnter (view);
  1812. }
  1813. }
  1814. /// <summary>
  1815. /// An <see cref="EventArgs"/> which allows passing a cancelable menu opening event or replacing with a new <see cref="MenuBarItem"/>.
  1816. /// </summary>
  1817. public class MenuOpeningEventArgs : EventArgs {
  1818. /// <summary>
  1819. /// The current <see cref="MenuBarItem"/> parent.
  1820. /// </summary>
  1821. public MenuBarItem CurrentMenu { get; }
  1822. /// <summary>
  1823. /// The new <see cref="MenuBarItem"/> to be replaced.
  1824. /// </summary>
  1825. public MenuBarItem NewMenuBarItem { get; set; }
  1826. /// <summary>
  1827. /// Flag that allows the cancellation of the event. If set to <see langword="true"/> in the
  1828. /// event handler, the event will be canceled.
  1829. /// </summary>
  1830. public bool Cancel { get; set; }
  1831. /// <summary>
  1832. /// Initializes a new instance of <see cref="MenuOpeningEventArgs"/>.
  1833. /// </summary>
  1834. /// <param name="currentMenu">The current <see cref="MenuBarItem"/> parent.</param>
  1835. public MenuOpeningEventArgs (MenuBarItem currentMenu)
  1836. {
  1837. CurrentMenu = currentMenu;
  1838. }
  1839. }
  1840. /// <summary>
  1841. /// An <see cref="EventArgs"/> which allows passing a cancelable menu closing event.
  1842. /// </summary>
  1843. public class MenuClosingEventArgs : EventArgs {
  1844. /// <summary>
  1845. /// The current <see cref="MenuBarItem"/> parent.
  1846. /// </summary>
  1847. public MenuBarItem CurrentMenu { get; }
  1848. /// <summary>
  1849. /// Indicates whether the current menu will reopen.
  1850. /// </summary>
  1851. public bool Reopen { get; }
  1852. /// <summary>
  1853. /// Indicates whether the current menu is a sub-menu.
  1854. /// </summary>
  1855. public bool IsSubMenu { get; }
  1856. /// <summary>
  1857. /// Flag that allows the cancellation of the event. If set to <see langword="true"/> in the
  1858. /// event handler, the event will be canceled.
  1859. /// </summary>
  1860. public bool Cancel { get; set; }
  1861. /// <summary>
  1862. /// Initializes a new instance of <see cref="MenuClosingEventArgs"/>.
  1863. /// </summary>
  1864. /// <param name="currentMenu">The current <see cref="MenuBarItem"/> parent.</param>
  1865. /// <param name="reopen">Whether the current menu will reopen.</param>
  1866. /// <param name="isSubMenu">Indicates whether it is a sub-menu.</param>
  1867. public MenuClosingEventArgs (MenuBarItem currentMenu, bool reopen, bool isSubMenu)
  1868. {
  1869. CurrentMenu = currentMenu;
  1870. Reopen = reopen;
  1871. IsSubMenu = isSubMenu;
  1872. }
  1873. }
  1874. }