Menu.cs 61 KB

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