EventLog.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #nullable enable
  2. using System;
  3. using System.Collections.ObjectModel;
  4. using Terminal.Gui;
  5. namespace UICatalog.Scenarios;
  6. /// <summary>
  7. /// An event log that automatically shows the events that are raised.
  8. /// </summary>
  9. /// <remarks>
  10. /// </remarks>
  11. public class EventLog : ListView
  12. {
  13. public EventLog ()
  14. {
  15. Title = "Event Log";
  16. CanFocus = true;
  17. X = Pos.AnchorEnd ();
  18. Y = 0;
  19. Width = Dim.Func (
  20. () =>
  21. {
  22. if (!IsInitialized)
  23. {
  24. return 0;
  25. }
  26. return Math.Min (SuperView!.Viewport.Width / 3, MaxLength + GetAdornmentsThickness ().Horizontal);
  27. });
  28. Height = Dim.Fill ();
  29. ExpandButton = new ()
  30. {
  31. Orientation = Orientation.Horizontal
  32. };
  33. Initialized += EventLog_Initialized;
  34. HorizontalScrollBar.AutoShow = true;
  35. VerticalScrollBar.AutoShow = true;
  36. AddCommand (
  37. Command.DeleteAll,
  38. () =>
  39. {
  40. _eventSource.Clear ();
  41. return true;
  42. });
  43. KeyBindings.Add (Key.Delete, Command.DeleteAll);
  44. }
  45. public ExpanderButton? ExpandButton { get; }
  46. private readonly ObservableCollection<string> _eventSource = [];
  47. private View? _viewToLog;
  48. public View? ViewToLog
  49. {
  50. get => _viewToLog;
  51. set
  52. {
  53. if (_viewToLog == value)
  54. {
  55. return;
  56. }
  57. _viewToLog = value;
  58. if (_viewToLog is { })
  59. {
  60. _viewToLog.Initialized += (s, args) =>
  61. {
  62. var sender = s as View;
  63. Log ($"Initialized: {GetIdentifyingString (sender)}");
  64. };
  65. _viewToLog.MouseClick += (s, args) => { Log ($"MouseClick: {args}"); };
  66. _viewToLog.MouseWheel += (s, args) => { Log ($"MouseWheel: {args}"); };
  67. _viewToLog.HandlingHotKey += (s, args) => { Log ($"HandlingHotKey: {args.Context}"); };
  68. _viewToLog.Selecting += (s, args) => { Log ($"Selecting: {args.Context}"); };
  69. _viewToLog.Accepting += (s, args) => { Log ($"Accepting: {args.Context}"); };
  70. }
  71. }
  72. }
  73. public void Log (string text)
  74. {
  75. _eventSource.Add (text);
  76. MoveEnd ();
  77. }
  78. private void EventLog_Initialized (object? _, EventArgs e)
  79. {
  80. Border?.Add (ExpandButton!);
  81. Source = new ListWrapper<string> (_eventSource);
  82. }
  83. private string GetIdentifyingString (View? view)
  84. {
  85. if (view is null)
  86. {
  87. return "null";
  88. }
  89. if (!string.IsNullOrEmpty (view.Title))
  90. {
  91. return view.Title;
  92. }
  93. if (!string.IsNullOrEmpty (view.Text))
  94. {
  95. return view.Text;
  96. }
  97. return view.GetType ().Name;
  98. }
  99. }