Menu.cs 61 KB

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