Menu.cs 61 KB

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