DevTools.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reactive.Disposables;
  4. using Avalonia.Controls;
  5. using Avalonia.Diagnostics.Views;
  6. using Avalonia.Input;
  7. using Avalonia.Interactivity;
  8. #nullable enable
  9. namespace Avalonia.Diagnostics
  10. {
  11. public static class DevTools
  12. {
  13. private static readonly Dictionary<TopLevel, Window> s_open = new Dictionary<TopLevel, Window>();
  14. public static IDisposable Attach(TopLevel root, KeyGesture gesture)
  15. {
  16. return Attach(root, new DevToolsOptions()
  17. {
  18. Gesture = gesture,
  19. });
  20. }
  21. public static IDisposable Attach(TopLevel root, DevToolsOptions options)
  22. {
  23. void PreviewKeyDown(object sender, KeyEventArgs e)
  24. {
  25. if (options.Gesture.Matches(e))
  26. {
  27. Open(root, options);
  28. }
  29. }
  30. return root.AddDisposableHandler(
  31. InputElement.KeyDownEvent,
  32. PreviewKeyDown,
  33. RoutingStrategies.Tunnel);
  34. }
  35. public static IDisposable Open(TopLevel root) => Open(root, new DevToolsOptions());
  36. public static IDisposable Open(TopLevel root, DevToolsOptions options)
  37. {
  38. if (s_open.TryGetValue(root, out var window))
  39. {
  40. window.Activate();
  41. }
  42. else
  43. {
  44. window = new MainWindow
  45. {
  46. Root = root,
  47. Width = options.Size.Width,
  48. Height = options.Size.Height,
  49. };
  50. window.Closed += DevToolsClosed;
  51. s_open.Add(root, window);
  52. if (options.ShowAsChildWindow && root is Window inspectedWindow)
  53. {
  54. window.Show(inspectedWindow);
  55. }
  56. else
  57. {
  58. window.Show();
  59. }
  60. }
  61. return Disposable.Create(() => window?.Close());
  62. }
  63. private static void DevToolsClosed(object sender, EventArgs e)
  64. {
  65. var window = (MainWindow)sender;
  66. s_open.Remove(window.Root);
  67. window.Closed -= DevToolsClosed;
  68. }
  69. }
  70. }