Menu.cs 59 KB

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