EventLog.cs 3.0 KB

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