Menu.cs 59 KB

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