-
Notifications
You must be signed in to change notification settings - Fork 673
/
Menu.cs
2094 lines (1890 loc) · 61.4 KB
/
Menu.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using NStack;
using System.Linq;
using System.Collections.Generic;
namespace Terminal.Gui {
/// <summary>
/// Specifies how a <see cref="MenuItem"/> shows selection state.
/// </summary>
[Flags]
public enum MenuItemCheckStyle {
/// <summary>
/// The menu item will be shown normally, with no check indicator. The default.
/// </summary>
NoCheck = 0b_0000_0000,
/// <summary>
/// The menu item will indicate checked/un-checked state (see <see cref="Checked"/>).
/// </summary>
Checked = 0b_0000_0001,
/// <summary>
/// The menu item is part of a menu radio group (see <see cref="Checked"/>) and will indicate selected state.
/// </summary>
Radio = 0b_0000_0010,
};
/// <summary>
/// A <see cref="MenuItem"/> has title, an associated help text, and an action to execute on activation.
/// MenuItems can also have a checked indicator (see <see cref="Checked"/>).
/// </summary>
public class MenuItem {
ustring title;
ShortcutHelper shortcutHelper;
internal int TitleLength => GetMenuBarItemLength (Title);
/// <summary>
/// Gets or sets arbitrary data for the menu item.
/// </summary>
/// <remarks>This property is not used internally.</remarks>
public object Data { get; set; }
/// <summary>
/// Initializes a new instance of <see cref="MenuItem"/>
/// </summary>
public MenuItem (Key shortcut = Key.Null) : this ("", "", null, null, null, shortcut) { }
/// <summary>
/// Initializes a new instance of <see cref="MenuItem"/>.
/// </summary>
/// <param name="title">Title for the menu item.</param>
/// <param name="help">Help text to display.</param>
/// <param name="action">Action to invoke when the menu item is activated.</param>
/// <param name="canExecute">Function to determine if the action can currently be executed.</param>
/// <param name="parent">The <see cref="Parent"/> of this menu item.</param>
/// <param name="shortcut">The <see cref="Shortcut"/> keystroke combination.</param>
public MenuItem (ustring title, ustring help, Action action, Func<bool> canExecute = null, MenuItem parent = null, Key shortcut = Key.Null)
{
Title = title ?? "";
Help = help ?? "";
Action = action;
CanExecute = canExecute;
Parent = parent;
shortcutHelper = new ShortcutHelper ();
if (shortcut != Key.Null) {
shortcutHelper.Shortcut = shortcut;
}
}
/// <summary>
/// The HotKey is used to activate a <see cref="MenuItem"/> with the keyboard. HotKeys are defined by prefixing the <see cref="Title"/>
/// of a MenuItem with an underscore ('_').
/// <para>
/// Pressing Alt-Hotkey for a <see cref="MenuBarItem"/> (menu items on the menu bar) works even if the menu is not active).
/// Once a menu has focus and is active, pressing just the HotKey will activate the MenuItem.
/// </para>
/// <para>
/// For example for a MenuBar with a "_File" MenuBarItem that contains a "_New" MenuItem, Alt-F will open the File menu.
/// Pressing the N key will then activate the New MenuItem.
/// </para>
/// <para>
/// See also <see cref="Shortcut"/> which enable global key-bindings to menu items.
/// </para>
/// </summary>
public Rune HotKey;
/// <summary>
/// Shortcut defines a key binding to the MenuItem that will invoke the MenuItem's action globally for the <see cref="View"/> that is
/// the parent of the <see cref="MenuBar"/> or <see cref="ContextMenu"/> this <see cref="MenuItem"/>.
/// <para>
/// The <see cref="Key"/> will be drawn on the MenuItem to the right of the <see cref="Title"/> and <see cref="Help"/> text. See <see cref="ShortcutTag"/>.
/// </para>
/// </summary>
public Key Shortcut {
get => shortcutHelper.Shortcut;
set {
if (shortcutHelper.Shortcut != value && (ShortcutHelper.PostShortcutValidation (value) || value == Key.Null)) {
shortcutHelper.Shortcut = value;
}
}
}
/// <summary>
/// Gets the text describing the keystroke combination defined by <see cref="Shortcut"/>.
/// </summary>
public ustring ShortcutTag => ShortcutHelper.GetShortcutTag (shortcutHelper.Shortcut);
/// <summary>
/// Gets or sets the title of the menu item .
/// </summary>
/// <value>The title.</value>
public ustring Title {
get { return title; }
set {
if (title != value) {
title = value;
GetHotKey ();
}
}
}
/// <summary>
/// Gets or sets the help text for the menu item. The help text is drawn to the right of the <see cref="Title"/>.
/// </summary>
/// <value>The help text.</value>
public ustring Help { get; set; }
/// <summary>
/// Gets or sets the action to be invoked when the menu item is triggered.
/// </summary>
/// <value>Method to invoke.</value>
public Action Action { get; set; }
/// <summary>
/// Gets or sets the action to be invoked to determine if the menu can be triggered. If <see cref="CanExecute"/> returns <see langword="true"/>
/// the menu item will be enabled. Otherwise, it will be disabled.
/// </summary>
/// <value>Function to determine if the action is can be executed or not.</value>
public Func<bool> CanExecute { get; set; }
/// <summary>
/// Returns <see langword="true"/> if the menu item is enabled. This method is a wrapper around <see cref="CanExecute"/>.
/// </summary>
public bool IsEnabled ()
{
return CanExecute == null ? true : CanExecute ();
}
//
// ┌─────────────────────────────┐
// │ Quit Quit UI Catalog Ctrl+Q │
// └─────────────────────────────┘
// ┌─────────────────┐
// │ ◌ TopLevel Alt+T │
// └─────────────────┘
// TODO: Replace the `2` literals with named constants
internal int Width => 1 + // space before Title
TitleLength +
2 + // space after Title - BUGBUG: This should be 1
(Checked || CheckType.HasFlag (MenuItemCheckStyle.Checked) || CheckType.HasFlag (MenuItemCheckStyle.Radio) ? 2 : 0) + // check glyph + space
(Help.ConsoleWidth > 0 ? 2 + Help.ConsoleWidth : 0) + // Two spaces before Help
(ShortcutTag.ConsoleWidth > 0 ? 2 + ShortcutTag.ConsoleWidth : 0); // Pad two spaces before shortcut tag (which are also aligned right)
/// <summary>
/// Sets or gets whether the <see cref="MenuItem"/> shows a check indicator or not. See <see cref="MenuItemCheckStyle"/>.
/// </summary>
public bool Checked { set; get; }
/// <summary>
/// Sets or gets the <see cref="MenuItemCheckStyle"/> of a menu item where <see cref="Checked"/> is set to <see langword="true"/>.
/// </summary>
public MenuItemCheckStyle CheckType { get; set; }
/// <summary>
/// Gets the parent for this <see cref="MenuItem"/>.
/// </summary>
/// <value>The parent.</value>
public MenuItem Parent { get; internal set; }
/// <summary>
/// Gets if this <see cref="MenuItem"/> is from a sub-menu.
/// </summary>
internal bool IsFromSubMenu { get { return Parent != null; } }
/// <summary>
/// Merely a debugging aid to see the interaction with main.
/// </summary>
public MenuItem GetMenuItem ()
{
return this;
}
/// <summary>
/// Merely a debugging aid to see the interaction with main.
/// </summary>
public bool GetMenuBarItem ()
{
return IsFromSubMenu;
}
void GetHotKey ()
{
bool nextIsHot = false;
foreach (var x in title) {
if (x == MenuBar.HotKeySpecifier) {
nextIsHot = true;
} else {
if (nextIsHot) {
HotKey = Char.ToUpper ((char)x);
break;
}
nextIsHot = false;
HotKey = default;
}
}
}
int GetMenuBarItemLength (ustring title)
{
int len = 0;
foreach (var ch in title) {
if (ch == MenuBar.HotKeySpecifier)
continue;
len += Math.Max (Rune.ColumnWidth (ch), 1);
}
return len;
}
}
/// <summary>
/// <see cref="MenuBarItem"/> is a menu item on an app's <see cref="MenuBar"/>.
/// MenuBarItems do not support <see cref="MenuItem.Shortcut"/>.
/// </summary>
public class MenuBarItem : MenuItem {
/// <summary>
/// Initializes a new <see cref="MenuBarItem"/> as a <see cref="MenuItem"/>.
/// </summary>
/// <param name="title">Title for the menu item.</param>
/// <param name="help">Help text to display. Will be displayed next to the Title surrounded by parentheses.</param>
/// <param name="action">Action to invoke when the menu item is activated.</param>
/// <param name="canExecute">Function to determine if the action can currently be executed.</param>
/// <param name="parent">The parent <see cref="MenuItem"/> of this if exist, otherwise is null.</param>
public MenuBarItem (ustring title, ustring help, Action action, Func<bool> canExecute = null, MenuItem parent = null) : base (title, help, action, canExecute, parent)
{
Initialize (title, null, null, true);
}
/// <summary>
/// Initializes a new <see cref="MenuBarItem"/>.
/// </summary>
/// <param name="title">Title for the menu item.</param>
/// <param name="children">The items in the current menu.</param>
/// <param name="parent">The parent <see cref="MenuItem"/> of this if exist, otherwise is null.</param>
public MenuBarItem (ustring title, MenuItem [] children, MenuItem parent = null)
{
Initialize (title, children, parent);
}
/// <summary>
/// Initializes a new <see cref="MenuBarItem"/> with separate list of items.
/// </summary>
/// <param name="title">Title for the menu item.</param>
/// <param name="children">The list of items in the current menu.</param>
/// <param name="parent">The parent <see cref="MenuItem"/> of this if exist, otherwise is null.</param>
public MenuBarItem (ustring title, List<MenuItem []> children, MenuItem parent = null)
{
Initialize (title, children, parent);
}
/// <summary>
/// Initializes a new <see cref="MenuBarItem"/>.
/// </summary>
/// <param name="children">The items in the current menu.</param>
public MenuBarItem (MenuItem [] children) : this ("", children) { }
/// <summary>
/// Initializes a new <see cref="MenuBarItem"/>.
/// </summary>
public MenuBarItem () : this (children: new MenuItem [] { }) { }
void Initialize (ustring title, object children, MenuItem parent = null, bool isTopLevel = false)
{
if (!isTopLevel && children == null) {
throw new ArgumentNullException (nameof (children), "The parameter cannot be null. Use an empty array instead.");
}
SetTitle (title ?? "");
if (parent != null) {
Parent = parent;
}
if (children is List<MenuItem []>) {
MenuItem [] childrens = new MenuItem [] { };
foreach (var item in (List<MenuItem []>)children) {
for (int i = 0; i < item.Length; i++) {
SetChildrensParent (item);
Array.Resize (ref childrens, childrens.Length + 1);
childrens [childrens.Length - 1] = item [i];
}
}
Children = childrens;
} else if (children is MenuItem []) {
SetChildrensParent ((MenuItem [])children);
Children = (MenuItem [])children;
} else {
Children = null;
}
}
void SetChildrensParent (MenuItem [] childrens)
{
foreach (var child in childrens) {
if (child != null && child.Parent == null) {
child.Parent = this;
}
}
}
/// <summary>
/// Check if the children parameter is a <see cref="MenuBarItem"/>.
/// </summary>
/// <param name="children"></param>
/// <returns>Returns a <see cref="MenuBarItem"/> or null otherwise.</returns>
public MenuBarItem SubMenu (MenuItem children)
{
return children as MenuBarItem;
}
/// <summary>
/// Check if the <see cref="MenuItem"/> parameter is a child of this.
/// </summary>
/// <param name="menuItem"></param>
/// <returns>Returns <c>true</c> if it is a child of this. <c>false</c> otherwise.</returns>
public bool IsSubMenuOf (MenuItem menuItem)
{
foreach (var child in Children) {
if (child == menuItem && child.Parent == menuItem.Parent) {
return true;
}
}
return false;
}
/// <summary>
/// Get the index of the <see cref="MenuItem"/> parameter.
/// </summary>
/// <param name="children"></param>
/// <returns>Returns a value bigger than -1 if the <see cref="MenuItem"/> is a child of this.</returns>
public int GetChildrenIndex (MenuItem children)
{
if (Children?.Length == 0) {
return -1;
}
int i = 0;
foreach (var child in Children) {
if (child == children) {
return i;
}
i++;
}
return -1;
}
void SetTitle (ustring title)
{
if (title == null)
title = ustring.Empty;
Title = title;
}
/// <summary>
/// Gets or sets an array of <see cref="MenuItem"/> objects that are the children of this <see cref="MenuBarItem"/>
/// </summary>
/// <value>The children.</value>
public MenuItem [] Children { get; set; }
internal bool IsTopLevel { get => Parent == null && (Children == null || Children.Length == 0) && Action != null; }
}
class Menu : View {
internal MenuBarItem barItems;
internal MenuBar host;
internal int current;
internal View previousSubFocused;
internal static Rect MakeFrame (int x, int y, MenuItem [] items, Menu parent = null)
{
if (items == null || items.Length == 0) {
return new Rect ();
}
int minX = x;
int minY = y;
int maxW = (items.Max (z => z?.Width) ?? 0) + 2; // This 2 is frame border?
int maxH = items.Length + 2; // This 2 is frame border?
if (parent != null && x + maxW > Driver.Cols) {
minX = Math.Max (parent.Frame.Right - parent.Frame.Width - maxW, 0);
}
if (y + maxH > Driver.Rows) {
minY = Math.Max (Driver.Rows - maxH, 0);
}
return new Rect (minX, minY, maxW, maxH);
}
public Menu (MenuBar host, int x, int y, MenuBarItem barItems, Menu parent = null)
: base (MakeFrame (x, y, barItems.Children, parent))
{
this.barItems = barItems;
this.host = host;
if (barItems.IsTopLevel) {
// This is a standalone MenuItem on a MenuBar
ColorScheme = host.ColorScheme;
CanFocus = true;
} else {
current = -1;
for (int i = 0; i < barItems.Children?.Length; i++) {
if (barItems.Children [i]?.IsEnabled () == true) {
current = i;
break;
}
}
ColorScheme = host.ColorScheme;
CanFocus = true;
WantMousePositionReports = host.WantMousePositionReports;
}
if (Application.Current != null) {
Application.Current.Resized += Current_Resized;
}
// Things this view knows how to do
AddCommand (Command.LineUp, () => MoveUp ());
AddCommand (Command.LineDown, () => MoveDown ());
AddCommand (Command.Left, () => { this.host.PreviousMenu (true); return true; });
AddCommand (Command.Right, () => {
this.host.NextMenu (!this.barItems.IsTopLevel || (this.barItems.Children != null
&& this.barItems.Children.Length > 0 && current > -1
&& current < this.barItems.Children.Length && this.barItems.Children [current].IsFromSubMenu),
this.barItems.Children != null && this.barItems.Children.Length > 0 && current > -1
&& host.UseSubMenusSingleFrame && this.barItems.SubMenu (this.barItems.Children [current]) != null);
return true;
});
AddCommand (Command.Cancel, () => { CloseAllMenus (); return true; });
AddCommand (Command.Accept, () => { RunSelected (); return true; });
// Default keybindings for this view
AddKeyBinding (Key.CursorUp, Command.LineUp);
AddKeyBinding (Key.CursorDown, Command.LineDown);
AddKeyBinding (Key.CursorLeft, Command.Left);
AddKeyBinding (Key.CursorRight, Command.Right);
AddKeyBinding (Key.Esc, Command.Cancel);
AddKeyBinding (Key.Enter, Command.Accept);
}
private void Current_Resized (Size obj)
{
if (host.IsMenuOpen) {
host.CloseAllMenus ();
}
}
internal Attribute DetermineColorSchemeFor (MenuItem item, int index)
{
if (item != null) {
if (index == current) return ColorScheme.Focus;
if (!item.IsEnabled ()) return ColorScheme.Disabled;
}
return GetNormalColor ();
}
// Draws the Menu, within the Frame
public override void Redraw (Rect bounds)
{
Driver.SetAttribute (GetNormalColor ());
DrawFrame (Bounds, padding: 0, fill: true);
for (int i = Bounds.Y; i < barItems.Children.Length; i++) {
if (i < 0)
continue;
var item = barItems.Children [i];
Driver.SetAttribute (item == null ? GetNormalColor ()
: i == current ? ColorScheme.Focus : GetNormalColor ());
if (item == null) {
Move (0, i + 1);
Driver.AddRune (Driver.LeftTee);
} else if (Frame.X + 1 < Driver.Cols)
Move (1, i + 1);
Driver.SetAttribute (DetermineColorSchemeFor (item, i));
for (int p = Bounds.X; p < Frame.Width - 2; p++) { // This - 2 is for the border
if (p < 0)
continue;
if (item == null)
Driver.AddRune (Driver.HLine);
else if (i == 0 && p == 0 && host.UseSubMenusSingleFrame && item.Parent.Parent != null)
Driver.AddRune (Driver.LeftArrow);
// This `- 3` is left border + right border + one row in from right
else if (p == Frame.Width - 3 && barItems.SubMenu (barItems.Children [i]) != null)
Driver.AddRune (Driver.RightArrow);
else
Driver.AddRune (' ');
}
if (item == null) {
if (SuperView?.Frame.Right - Frame.X > Frame.Width - 1) {
Move (Frame.Width - 1, i + 1);
Driver.AddRune (Driver.RightTee);
}
continue;
}
ustring textToDraw;
var checkChar = Driver.Selected;
var uncheckedChar = Driver.UnSelected;
if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked)) {
checkChar = Driver.Checked;
uncheckedChar = Driver.UnChecked;
}
// Support Checked even though CheckType wasn't set
if (item.Checked) {
textToDraw = ustring.Make (new Rune [] { checkChar, ' ' }) + item.Title;
} else if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked) || item.CheckType.HasFlag (MenuItemCheckStyle.Radio)) {
textToDraw = ustring.Make (new Rune [] { uncheckedChar, ' ' }) + item.Title;
} else {
textToDraw = item.Title;
}
ViewToScreen (2, i + 1, out int vtsCol, out _, false);
if (vtsCol < Driver.Cols) {
Move (2, i + 1);
if (!item.IsEnabled ()) {
DrawHotString (textToDraw, ColorScheme.Disabled, ColorScheme.Disabled);
} else if (i == 0 && host.UseSubMenusSingleFrame && item.Parent.Parent != null) {
var tf = new TextFormatter () {
Alignment = TextAlignment.Centered,
HotKeySpecifier = MenuBar.HotKeySpecifier,
Text = textToDraw
};
// The -3 is left/right border + one space (not sure what for)
tf.Draw (ViewToScreen (new Rect (2, i + 1, Frame.Width - 3, 1)),
i == current ? ColorScheme.Focus : GetNormalColor (),
i == current ? ColorScheme.HotFocus : ColorScheme.HotNormal,
SuperView == null ? default : SuperView.ViewToScreen (SuperView.Bounds));
} else {
DrawHotString (textToDraw,
i == current ? ColorScheme.HotFocus : ColorScheme.HotNormal,
i == current ? ColorScheme.Focus : GetNormalColor ());
}
// The help string
var l = item.ShortcutTag.ConsoleWidth == 0 ? item.Help.ConsoleWidth : item.Help.ConsoleWidth + item.ShortcutTag.ConsoleWidth + 2;
var col = Frame.Width - l - 2;
ViewToScreen (col, i + 1, out vtsCol, out _, false);
if (vtsCol < Driver.Cols) {
Move (col, 1 + i);
Driver.AddStr (item.Help);
// The shortcut tag string
if (!item.ShortcutTag.IsEmpty) {
l = item.ShortcutTag.ConsoleWidth;
Move (Frame.Width - l - 2, 1 + i);
Driver.AddStr (item.ShortcutTag);
}
}
}
}
PositionCursor ();
}
public override void PositionCursor ()
{
if (host == null || host.IsMenuOpen)
if (barItems.IsTopLevel) {
host.PositionCursor ();
} else
Move (2, 1 + current);
else
host.PositionCursor ();
}
public void Run (Action action)
{
if (action == null || host == null)
return;
Application.UngrabMouse ();
host.CloseAllMenus ();
Application.Refresh ();
host.Run (action);
}
public override bool OnLeave (View view)
{
return host.OnLeave (view);
}
public override bool OnKeyDown (KeyEvent keyEvent)
{
if (keyEvent.IsAlt) {
host.CloseAllMenus ();
return true;
}
return false;
}
public override bool ProcessHotKey (KeyEvent keyEvent)
{
// To ncurses simulate a AltMask key pressing Alt+Space because
// it can�t detect an alone special key down was pressed.
if (keyEvent.IsAlt && keyEvent.Key == Key.AltMask) {
OnKeyDown (keyEvent);
return true;
}
return false;
}
public override bool ProcessKey (KeyEvent kb)
{
var result = InvokeKeybindings (kb);
if (result != null)
return (bool)result;
// TODO: rune-ify
if (barItems.Children != null && Char.IsLetterOrDigit ((char)kb.KeyValue)) {
var x = Char.ToUpper ((char)kb.KeyValue);
var idx = -1;
foreach (var item in barItems.Children) {
idx++;
if (item == null) continue;
if (item.IsEnabled () && item.HotKey == x) {
current = idx;
RunSelected ();
return true;
}
}
}
return host.ProcessHotKey (kb);
}
void RunSelected ()
{
if (barItems.IsTopLevel) {
Run (barItems.Action);
} else if (current > -1 && barItems.Children [current].Action != null) {
Run (barItems.Children [current].Action);
} else if (current == 0 && host.UseSubMenusSingleFrame
&& barItems.Children [current].Parent.Parent != null) {
host.PreviousMenu (barItems.Children [current].Parent.IsFromSubMenu, true);
} else if (current > -1 && barItems.SubMenu (barItems.Children [current]) != null) {
CheckSubMenu ();
}
}
void CloseAllMenus ()
{
Application.UngrabMouse ();
host.CloseAllMenus ();
}
bool MoveDown ()
{
if (barItems.IsTopLevel) {
return true;
}
bool disabled;
do {
current++;
if (current >= barItems.Children.Length) {
current = 0;
}
if (this != host.openCurrentMenu && barItems.Children [current]?.IsFromSubMenu == true && host.selectedSub > -1) {
host.PreviousMenu (true);
host.SelectEnabledItem (barItems.Children, current, out current);
host.openCurrentMenu = this;
}
var item = barItems.Children [current];
if (item?.IsEnabled () != true) {
disabled = true;
} else {
disabled = false;
}
if (!host.UseSubMenusSingleFrame && host.UseKeysUpDownAsKeysLeftRight && barItems.SubMenu (barItems.Children [current]) != null &&
!disabled && host.IsMenuOpen) {
if (!CheckSubMenu ())
return false;
break;
}
if (!host.IsMenuOpen) {
host.OpenMenu (host.selected);
}
} while (barItems.Children [current] == null || disabled);
SetNeedsDisplay ();
SetParentSetNeedsDisplay ();
if (!host.UseSubMenusSingleFrame)
host.OnMenuOpened ();
return true;
}
bool MoveUp ()
{
if (barItems.IsTopLevel || current == -1) {
return true;
}
bool disabled;
do {
current--;
if (host.UseKeysUpDownAsKeysLeftRight && !host.UseSubMenusSingleFrame) {
if ((current == -1 || this != host.openCurrentMenu) && barItems.Children [current + 1].IsFromSubMenu && host.selectedSub > -1) {
current++;
host.PreviousMenu (true);
if (current > 0) {
current--;
host.openCurrentMenu = this;
}
break;
}
}
if (current < 0)
current = barItems.Children.Length - 1;
if (!host.SelectEnabledItem (barItems.Children, current, out current, false)) {
current = 0;
if (!host.SelectEnabledItem (barItems.Children, current, out current) && !host.CloseMenu (false)) {
return false;
}
break;
}
var item = barItems.Children [current];
if (item?.IsEnabled () != true) {
disabled = true;
} else {
disabled = false;
}
if (!host.UseSubMenusSingleFrame && host.UseKeysUpDownAsKeysLeftRight && barItems.SubMenu (barItems.Children [current]) != null &&
!disabled && host.IsMenuOpen) {
if (!CheckSubMenu ())
return false;
break;
}
} while (barItems.Children [current] == null || disabled);
SetNeedsDisplay ();
SetParentSetNeedsDisplay ();
if (!host.UseSubMenusSingleFrame)
host.OnMenuOpened ();
return true;
}
private void SetParentSetNeedsDisplay ()
{
if (host.openSubMenu != null) {
foreach (var menu in host.openSubMenu) {
menu.SetNeedsDisplay ();
}
}
host?.openMenu.SetNeedsDisplay ();
host.SetNeedsDisplay ();
}
public override bool MouseEvent (MouseEvent me)
{
if (!host.handled && !host.HandleGrabView (me, this)) {
return false;
}
host.handled = false;
bool disabled;
if (me.Flags == MouseFlags.Button1Clicked) {
disabled = false;
if (me.Y < 1)
return true;
var meY = me.Y - 1;
if (meY >= barItems.Children.Length)
return true;
var item = barItems.Children [meY];
if (item == null || !item.IsEnabled ()) disabled = true;
if (disabled) return true;
current = meY;
if (item != null && !disabled)
RunSelected ();
return true;
} else if (me.Flags == MouseFlags.Button1Pressed || me.Flags == MouseFlags.Button1DoubleClicked ||
me.Flags == MouseFlags.Button1TripleClicked || me.Flags == MouseFlags.ReportMousePosition ||
me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
disabled = false;
if (me.Y < 1 || me.Y - 1 >= barItems.Children.Length) {
return true;
}
var item = barItems.Children [me.Y - 1];
if (item == null) return true;
if (item == null || !item.IsEnabled ()) disabled = true;
if (item != null && !disabled)
current = me.Y - 1;
if (host.UseSubMenusSingleFrame || !CheckSubMenu ()) {
SetNeedsDisplay ();
SetParentSetNeedsDisplay ();
return true;
}
host.OnMenuOpened ();
return true;
}
return false;
}
internal bool CheckSubMenu ()
{
if (current == -1 || barItems.Children [current] == null) {
return true;
}
var subMenu = barItems.SubMenu (barItems.Children [current]);
if (subMenu != null) {
int pos = -1;
if (host.openSubMenu != null) {
pos = host.openSubMenu.FindIndex (o => o?.barItems == subMenu);
}
if (pos == -1 && this != host.openCurrentMenu && subMenu.Children != host.openCurrentMenu.barItems.Children
&& !host.CloseMenu (false, true)) {
return false;
}
host.Activate (host.selected, pos, subMenu);
} else if (host.openSubMenu?.Count == 0 || host.openSubMenu?.Last ().barItems.IsSubMenuOf (barItems.Children [current]) == false) {
return host.CloseMenu (false, true);
} else {
SetNeedsDisplay ();
SetParentSetNeedsDisplay ();
}
return true;
}
int GetSubMenuIndex (MenuBarItem subMenu)
{
int pos = -1;
if (this != null && Subviews.Count > 0) {
Menu v = null;
foreach (var menu in Subviews) {
if (((Menu)menu).barItems == subMenu)
v = (Menu)menu;
}
if (v != null)
pos = Subviews.IndexOf (v);
}
return pos;
}
///<inheritdoc/>
public override bool OnEnter (View view)
{
Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
return base.OnEnter (view);
}
protected override void Dispose (bool disposing)
{
if (Application.Current != null) {
Application.Current.Resized -= Current_Resized;
}
base.Dispose (disposing);
}
}
/// <summary>
/// <para>
/// Provides a menu bar that spans the top of a <see cref="Toplevel"/> View with drop-down and cascading menus.
/// </para>
/// <para>
/// By default, any sub-sub-menus (sub-menus of the <see cref="MenuItem"/>s added to <see cref="MenuBarItem"/>s)
/// are displayed in a cascading manner, where each sub-sub-menu pops out of the sub-menu frame
/// (either to the right or left, depending on where the sub-menu is relative to the edge of the screen). By setting
/// <see cref="UseSubMenusSingleFrame"/> to <see langword="true"/>, this behavior can be changed such that all sub-sub-menus are
/// drawn within a single frame below the MenuBar.
/// </para>
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="MenuBar"/> appears on the first row of the parent <see cref="Toplevel"/> View and uses the full width.
/// </para>
/// <para>
/// The <see cref="MenuBar"/> provides global hotkeys for the application. See <see cref="MenuItem.HotKey"/>.
/// </para>
/// <para>
/// See also: <see cref="ContextMenu"/>
/// </para>
/// </remarks>
public class MenuBar : View {
internal int selected;
internal int selectedSub;
/// <summary>
/// Gets or sets the array of <see cref="MenuBarItem"/>s for the menu. Only set this after the <see cref="MenuBar"/> is visible.
/// </summary>
/// <value>The menu array.</value>
public MenuBarItem [] Menus { get; set; }
private bool useKeysUpDownAsKeysLeftRight = false;
/// <summary>
/// Used for change the navigation key style.
/// </summary>
public bool UseKeysUpDownAsKeysLeftRight {
get => useKeysUpDownAsKeysLeftRight;
set {
useKeysUpDownAsKeysLeftRight = value;
if (value && UseSubMenusSingleFrame) {
UseSubMenusSingleFrame = false;
SetNeedsDisplay ();
}
}
}
static ustring shortcutDelimiter = "+";
/// <summary>
/// Sets or gets the shortcut delimiter separator. The default is "+".
/// </summary>
public static ustring ShortcutDelimiter {
get => shortcutDelimiter;
set {
if (shortcutDelimiter != value) {
shortcutDelimiter = value == ustring.Empty ? " " : value;
}
}
}
/// <summary>
/// The specifier character for the hotkey to all menus.
/// </summary>
new public static Rune HotKeySpecifier => '_';
private bool useSubMenusSingleFrame;
/// <summary>
/// Gets or sets if the sub-menus must be displayed in a single or multiple frames.
/// <para>
/// By default any sub-sub-menus (sub-menus of the main <see cref="MenuItem"/>s) are displayed in a cascading manner,
/// where each sub-sub-menu pops out of the sub-menu frame
/// (either to the right or left, depending on where the sub-menu is relative to the edge of the screen). By setting
/// <see cref="UseSubMenusSingleFrame"/> to <see langword="true"/>, this behavior can be changed such that all sub-sub-menus are
/// drawn within a single frame below the MenuBar.
/// </para>
/// </summary>
public bool UseSubMenusSingleFrame {
get => useSubMenusSingleFrame;
set {
useSubMenusSingleFrame = value;
if (value && UseKeysUpDownAsKeysLeftRight) {
useKeysUpDownAsKeysLeftRight = false;
SetNeedsDisplay ();
}
}
}
/// <summary>
/// The <see cref="Gui.Key"/> used to activate the menu bar by keyboard.
/// </summary>
public Key Key { get; set; } = Key.F9;
///<inheritdoc/>
public override bool Visible {
get => base.Visible;
set {
base.Visible = value;
if (!value) {
CloseAllMenus ();
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="MenuBar"/>.
/// </summary>
public MenuBar () : this (new MenuBarItem [] { }) { }
/// <summary>
/// Initializes a new instance of the <see cref="MenuBar"/> class with the specified set of toplevel menu items.
/// </summary>
/// <param name="menus">Individual menu items; a null item will result in a separator being drawn.</param>
public MenuBar (MenuBarItem [] menus) : base ()
{
X = 0;
Y = 0;
Width = Dim.Fill ();
Height = 1;
Menus = menus;
//CanFocus = true;
selected = -1;
selectedSub = -1;
ColorScheme = Colors.Menu;
WantMousePositionReports = true;
IsMenuOpen = false;
// Things this view knows how to do