EventLog.cs 3.1 KB

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