Menu.cs 58 KB

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