Menu.cs 60 KB

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