Clipboard.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #nullable enable
  2. namespace Terminal.Gui.App;
  3. /// <summary>Provides cut, copy, and paste support for the OS clipboard.</summary>
  4. /// <remarks>
  5. /// <para>On Windows, the <see cref="Clipboard"/> class uses the Windows Clipboard APIs via P/Invoke.</para>
  6. /// <para>
  7. /// On Linux, when not running under Windows Subsystem for Linux (WSL), the <see cref="Clipboard"/> class uses
  8. /// the xclip command line tool. If xclip is not installed, the clipboard will not work.
  9. /// </para>
  10. /// <para>
  11. /// On Linux, when running under Windows Subsystem for Linux (WSL), the <see cref="Clipboard"/> class launches
  12. /// Windows' powershell.exe via WSL interop and uses the "Set-Clipboard" and "Get-Clipboard" Powershell CmdLets.
  13. /// </para>
  14. /// <para>
  15. /// On the Mac, the <see cref="Clipboard"/> class uses the MacO OS X pbcopy and pbpaste command line tools and
  16. /// the Mac clipboard APIs vai P/Invoke.
  17. /// </para>
  18. /// </remarks>
  19. public static class Clipboard
  20. {
  21. private static string? _contents = string.Empty;
  22. /// <summary>Gets (copies from) or sets (pastes to) the contents of the OS clipboard.</summary>
  23. public static string? Contents
  24. {
  25. get
  26. {
  27. try
  28. {
  29. if (IsSupported)
  30. {
  31. // throw new InvalidOperationException ($"{Application.Driver?.GetType ().Name}.GetClipboardData returned null instead of string.Empty");
  32. string? clipData = Application.Driver?.Clipboard?.GetClipboardData () ?? string.Empty;
  33. _contents = clipData;
  34. }
  35. }
  36. catch (Exception)
  37. {
  38. _contents = string.Empty;
  39. }
  40. return _contents;
  41. }
  42. set
  43. {
  44. try
  45. {
  46. if (IsSupported)
  47. {
  48. value ??= string.Empty;
  49. Application.Driver?.Clipboard?.SetClipboardData (value);
  50. }
  51. _contents = value;
  52. }
  53. catch (Exception)
  54. {
  55. _contents = value;
  56. }
  57. }
  58. }
  59. /// <summary>Returns true if the environmental dependencies are in place to interact with the OS clipboard.</summary>
  60. /// <remarks></remarks>
  61. public static bool IsSupported => Application.Driver?.Clipboard?.IsSupported ?? false;
  62. }