Menu.cs 66 KB

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