Clipboard.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. using System.Text;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Threading.Tasks;
  5. namespace Terminal.Gui;
  6. /// <summary>
  7. /// Provides cut, copy, and paste support for the OS clipboard.
  8. /// </summary>
  9. /// <remarks>
  10. /// <para>
  11. /// On Windows, the <see cref="Clipboard"/> class uses the Windows Clipboard APIs via P/Invoke.
  12. /// </para>
  13. /// <para>
  14. /// On Linux, when not running under Windows Subsystem for Linux (WSL),
  15. /// the <see cref="Clipboard"/> class uses the xclip command line tool. If xclip is not installed,
  16. /// the clipboard will not work.
  17. /// </para>
  18. /// <para>
  19. /// On Linux, when running under Windows Subsystem for Linux (WSL),
  20. /// the <see cref="Clipboard"/> class launches Windows' powershell.exe via WSL interop and uses the
  21. /// "Set-Clipboard" and "Get-Clipboard" Powershell CmdLets.
  22. /// </para>
  23. /// <para>
  24. /// On the Mac, the <see cref="Clipboard"/> class uses the MacO OS X pbcopy and pbpaste command line tools
  25. /// and the Mac clipboard APIs vai P/Invoke.
  26. /// </para>
  27. /// </remarks>
  28. public static class Clipboard {
  29. static string _contents = string.Empty;
  30. /// <summary>
  31. /// Gets (copies from) or sets (pastes to) the contents of the OS clipboard.
  32. /// </summary>
  33. public static string Contents {
  34. get {
  35. try {
  36. if (IsSupported) {
  37. var clipData = Application.Driver.Clipboard.GetClipboardData ();
  38. if (clipData == null) {
  39. // throw new InvalidOperationException ($"{Application.Driver.GetType ().Name}.GetClipboardData returned null instead of string.Empty");
  40. clipData = string.Empty;
  41. }
  42. _contents = clipData;
  43. }
  44. } catch (Exception) {
  45. _contents = string.Empty;
  46. }
  47. return _contents;
  48. }
  49. set {
  50. try {
  51. if (IsSupported) {
  52. if (value == null) {
  53. value = string.Empty;
  54. }
  55. Application.Driver.Clipboard.SetClipboardData (value);
  56. }
  57. _contents = value;
  58. } catch (Exception) {
  59. _contents = value;
  60. }
  61. }
  62. }
  63. /// <summary>
  64. /// Returns true if the environmental dependencies are in place to interact with the OS clipboard.
  65. /// </summary>
  66. /// <remarks>
  67. /// </remarks>
  68. public static bool IsSupported { get => Application.Driver.Clipboard.IsSupported; }
  69. /// <summary>
  70. /// Copies the _contents of the OS clipboard to <paramref name="result"/> if possible.
  71. /// </summary>
  72. /// <param name="result">The _contents of the OS clipboard if successful, <see cref="string.Empty"/> if not.</param>
  73. /// <returns><see langword="true"/> the OS clipboard was retrieved, <see langword="false"/> otherwise.</returns>
  74. public static bool TryGetClipboardData (out string result)
  75. {
  76. if (IsSupported && Application.Driver.Clipboard.TryGetClipboardData (out result)) {
  77. if (_contents != result) {
  78. _contents = result;
  79. }
  80. return true;
  81. }
  82. result = string.Empty;
  83. return false;
  84. }
  85. /// <summary>
  86. /// Pastes the <paramref name="text"/> to the OS clipboard if possible.
  87. /// </summary>
  88. /// <param name="text">The text to paste to the OS clipboard.</param>
  89. /// <returns><see langword="true"/> the OS clipboard was set, <see langword="false"/> otherwise.</returns>
  90. public static bool TrySetClipboardData (string text)
  91. {
  92. if (IsSupported && Application.Driver.Clipboard.TrySetClipboardData (text)) {
  93. _contents = text;
  94. return true;
  95. }
  96. return false;
  97. }
  98. }
  99. /// <summary>
  100. /// Helper class for console drivers to invoke shell commands to interact with the clipboard.
  101. /// Used primarily by CursesDriver, but also used in Unit tests which is why it is in
  102. /// ConsoleDriver.cs.
  103. /// </summary>
  104. internal static class ClipboardProcessRunner {
  105. public static (int exitCode, string result) Bash (string commandLine, string inputText = "", bool waitForOutput = false)
  106. {
  107. var arguments = $"-c \"{commandLine}\"";
  108. var (exitCode, result) = Process ("bash", arguments, inputText, waitForOutput);
  109. return (exitCode, result.TrimEnd ());
  110. }
  111. public static (int exitCode, string result) Process (string cmd, string arguments, string input = null, bool waitForOutput = true)
  112. {
  113. var output = string.Empty;
  114. using (Process process = new Process {
  115. StartInfo = new ProcessStartInfo {
  116. FileName = cmd,
  117. Arguments = arguments,
  118. RedirectStandardOutput = true,
  119. RedirectStandardError = true,
  120. RedirectStandardInput = true,
  121. UseShellExecute = false,
  122. CreateNoWindow = true,
  123. }
  124. }) {
  125. var eventHandled = new TaskCompletionSource<bool> ();
  126. process.Start ();
  127. if (!string.IsNullOrEmpty (input)) {
  128. process.StandardInput.Write (input);
  129. process.StandardInput.Close ();
  130. }
  131. if (!process.WaitForExit (5000)) {
  132. var timeoutError = $@"Process timed out. Command line: {process.StartInfo.FileName} {process.StartInfo.Arguments}.";
  133. throw new TimeoutException (timeoutError);
  134. }
  135. if (waitForOutput && process.StandardOutput.Peek () != -1) {
  136. output = process.StandardOutput.ReadToEnd ();
  137. }
  138. if (process.ExitCode > 0) {
  139. output = $@"Process failed to run. Command line: {cmd} {arguments}.
  140. Output: {output}
  141. Error: {process.StandardError.ReadToEnd ()}";
  142. }
  143. return (process.ExitCode, output);
  144. }
  145. }
  146. public static bool DoubleWaitForExit (this System.Diagnostics.Process process)
  147. {
  148. var result = process.WaitForExit (500);
  149. if (result) {
  150. process.WaitForExit ();
  151. }
  152. return result;
  153. }
  154. public static bool FileExists (this string value)
  155. {
  156. return !string.IsNullOrEmpty (value) && !value.Contains ("not found");
  157. }
  158. }