Menu.cs 60 KB

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