Menu.cs 59 KB

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