Clipboard.cs 2.4 KB

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