Clipboard.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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 (NotSupportedException e) {
  59. throw e;
  60. } catch (Exception) {
  61. _contents = value;
  62. }
  63. }
  64. }
  65. /// <summary>
  66. /// Returns true if the environmental dependencies are in place to interact with the OS clipboard.
  67. /// </summary>
  68. /// <remarks>
  69. /// </remarks>
  70. public static bool IsSupported { get => Application.Driver.Clipboard.IsSupported; }
  71. /// <summary>
  72. /// Copies the _contents of the OS clipboard to <paramref name="result"/> if possible.
  73. /// </summary>
  74. /// <param name="result">The _contents of the OS clipboard if successful, <see cref="string.Empty"/> if not.</param>
  75. /// <returns><see langword="true"/> the OS clipboard was retrieved, <see langword="false"/> otherwise.</returns>
  76. public static bool TryGetClipboardData (out string result)
  77. {
  78. if (IsSupported && Application.Driver.Clipboard.TryGetClipboardData (out result)) {
  79. if (_contents != result) {
  80. _contents = result;
  81. }
  82. return true;
  83. }
  84. result = string.Empty;
  85. return false;
  86. }
  87. /// <summary>
  88. /// Pastes the <paramref name="text"/> to the OS clipboard if possible.
  89. /// </summary>
  90. /// <param name="text">The text to paste to the OS clipboard.</param>
  91. /// <returns><see langword="true"/> the OS clipboard was set, <see langword="false"/> otherwise.</returns>
  92. public static bool TrySetClipboardData (string text)
  93. {
  94. if (IsSupported && Application.Driver.Clipboard.TrySetClipboardData (text)) {
  95. _contents = text;
  96. return true;
  97. }
  98. return false;
  99. }
  100. }
  101. /// <summary>
  102. /// Helper class for console drivers to invoke shell commands to interact with the clipboard.
  103. /// Used primarily by CursesDriver, but also used in Unit tests which is why it is in
  104. /// ConsoleDriver.cs.
  105. /// </summary>
  106. internal static class ClipboardProcessRunner {
  107. public static (int exitCode, string result) Bash (string commandLine, string inputText = "", bool waitForOutput = false)
  108. {
  109. var arguments = $"-c \"{commandLine}\"";
  110. var (exitCode, result) = Process ("bash", arguments, inputText, waitForOutput);
  111. return (exitCode, result.TrimEnd ());
  112. }
  113. public static (int exitCode, string result) Process (string cmd, string arguments, string input = null, bool waitForOutput = true)
  114. {
  115. var output = string.Empty;
  116. using (Process process = new Process {
  117. StartInfo = new ProcessStartInfo {
  118. FileName = cmd,
  119. Arguments = arguments,
  120. RedirectStandardOutput = true,
  121. RedirectStandardError = true,
  122. RedirectStandardInput = true,
  123. UseShellExecute = false,
  124. CreateNoWindow = true,
  125. }
  126. }) {
  127. var eventHandled = new TaskCompletionSource<bool> ();
  128. process.Start ();
  129. if (!string.IsNullOrEmpty (input)) {
  130. process.StandardInput.Write (input);
  131. process.StandardInput.Close ();
  132. }
  133. if (!process.WaitForExit (5000)) {
  134. var timeoutError = $@"Process timed out. Command line: {process.StartInfo.FileName} {process.StartInfo.Arguments}.";
  135. throw new TimeoutException (timeoutError);
  136. }
  137. if (waitForOutput && process.StandardOutput.Peek () != -1) {
  138. output = process.StandardOutput.ReadToEnd ();
  139. }
  140. if (process.ExitCode > 0) {
  141. output = $@"Process failed to run. Command line: {cmd} {arguments}.
  142. Output: {output}
  143. Error: {process.StandardError.ReadToEnd ()}";
  144. }
  145. return (process.ExitCode, output);
  146. }
  147. }
  148. public static bool DoubleWaitForExit (this System.Diagnostics.Process process)
  149. {
  150. var result = process.WaitForExit (500);
  151. if (result) {
  152. process.WaitForExit ();
  153. }
  154. return result;
  155. }
  156. public static bool FileExists (this string value)
  157. {
  158. return !string.IsNullOrEmpty (value) && !value.Contains ("not found");
  159. }
  160. }