EventLog.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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, args) =>
  60. {
  61. var sender = s as View;
  62. Log ($"Initialized: {GetIdentifyingString (sender)}");
  63. };
  64. _viewToLog.MouseClick += (s, args) => { Log ($"MouseClick: {args}"); };
  65. _viewToLog.MouseWheel += (s, args) => { Log ($"MouseWheel: {args}"); };
  66. _viewToLog.HandlingHotKey += (s, args) => { Log ($"HandlingHotKey: {args.Context}"); };
  67. _viewToLog.Selecting += (s, args) => { Log ($"Selecting: {args.Context}"); };
  68. _viewToLog.Accepting += (s, args) => { Log ($"Accepting: {args.Context}"); };
  69. }
  70. }
  71. }
  72. public void Log (string text)
  73. {
  74. _eventSource.Add (text);
  75. MoveEnd ();
  76. }
  77. private void EventLog_Initialized (object? _, EventArgs e)
  78. {
  79. Border?.Add (ExpandButton!);
  80. Source = new ListWrapper<string> (_eventSource);
  81. }
  82. private string GetIdentifyingString (View? view)
  83. {
  84. if (view is null)
  85. {
  86. return "null";
  87. }
  88. if (!string.IsNullOrEmpty (view.Title))
  89. {
  90. return view.Title;
  91. }
  92. if (!string.IsNullOrEmpty (view.Text))
  93. {
  94. return view.Text;
  95. }
  96. return view.GetType ().Name;
  97. }
  98. }