UnixClipboard.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. using System.Runtime.InteropServices;
  2. namespace Terminal.Gui.Drivers;
  3. /// <summary>A clipboard implementation for Unix that uses the xclip command to access the clipboard.</summary>
  4. /// <remarks>If xclip is not installed, this implementation will not work.</remarks>
  5. internal class UnixClipboard : ClipboardBase
  6. {
  7. private string _xclipPath = string.Empty;
  8. public UnixClipboard () { IsSupported = CheckSupport (); }
  9. public override bool IsSupported { get; }
  10. protected override string GetClipboardDataImpl ()
  11. {
  12. string tempFileName = Path.GetTempFileName ();
  13. var xclipargs = "-selection clipboard -o";
  14. try
  15. {
  16. (int exitCode, string result) =
  17. ClipboardProcessRunner.Bash ($"{_xclipPath} {xclipargs} > {tempFileName}", waitForOutput: false);
  18. if (exitCode == 0)
  19. {
  20. return File.ReadAllText (tempFileName);
  21. }
  22. }
  23. catch (Exception e)
  24. {
  25. throw new NotSupportedException ($"\"{_xclipPath} {xclipargs}\" failed.", e);
  26. }
  27. finally
  28. {
  29. File.Delete (tempFileName);
  30. }
  31. return string.Empty;
  32. }
  33. protected override void SetClipboardDataImpl (string text)
  34. {
  35. var xclipargs = "-selection clipboard -i";
  36. try
  37. {
  38. (int exitCode, _) = ClipboardProcessRunner.Bash ($"{_xclipPath} {xclipargs}", text);
  39. }
  40. catch (Exception e)
  41. {
  42. throw new NotSupportedException ($"\"{_xclipPath} {xclipargs} < {text}\" failed", e);
  43. }
  44. }
  45. private bool CheckSupport ()
  46. {
  47. #pragma warning disable RCS1075 // Avoid empty catch clause that catches System.Exception.
  48. try
  49. {
  50. (int exitCode, string result) = ClipboardProcessRunner.Bash ("which xclip", waitForOutput: true);
  51. if (exitCode == 0 && result.FileExists ())
  52. {
  53. _xclipPath = result;
  54. return true;
  55. }
  56. }
  57. catch (Exception)
  58. {
  59. // Permissions issue.
  60. }
  61. #pragma warning restore RCS1075 // Avoid empty catch clause that catches System.Exception.
  62. return false;
  63. }
  64. }
  65. /// <summary>
  66. /// A clipboard implementation for MacOSX. This implementation uses the Mac clipboard API (via P/Invoke) to
  67. /// copy/paste. The existence of the Mac pbcopy and pbpaste commands is used to determine if copy/paste is supported.
  68. /// </summary>
  69. internal class MacOSXClipboard : ClipboardBase
  70. {
  71. private readonly nint _allocRegister = sel_registerName ("alloc");
  72. private readonly nint _clearContentsRegister = sel_registerName ("clearContents");
  73. private readonly nint _generalPasteboard;
  74. private readonly nint _generalPasteboardRegister = sel_registerName ("generalPasteboard");
  75. private readonly nint _initWithUtf8Register = sel_registerName ("initWithUTF8String:");
  76. private readonly nint _nsPasteboard = objc_getClass ("NSPasteboard");
  77. private readonly nint _nsString = objc_getClass ("NSString");
  78. private readonly nint _nsStringPboardType;
  79. private readonly nint _setStringRegister = sel_registerName ("setString:forType:");
  80. private readonly nint _stringForTypeRegister = sel_registerName ("stringForType:");
  81. private readonly nint _utf8Register = sel_registerName ("UTF8String");
  82. private readonly nint _utfTextType;
  83. public MacOSXClipboard ()
  84. {
  85. _utfTextType = objc_msgSend (
  86. objc_msgSend (_nsString, _allocRegister),
  87. _initWithUtf8Register,
  88. "public.utf8-plain-text"
  89. );
  90. _nsStringPboardType = objc_msgSend (
  91. objc_msgSend (_nsString, _allocRegister),
  92. _initWithUtf8Register,
  93. "NSStringPboardType"
  94. );
  95. _generalPasteboard = objc_msgSend (_nsPasteboard, _generalPasteboardRegister);
  96. IsSupported = CheckSupport ();
  97. }
  98. public override bool IsSupported { get; }
  99. protected override string GetClipboardDataImpl ()
  100. {
  101. nint ptr = objc_msgSend (_generalPasteboard, _stringForTypeRegister, _nsStringPboardType);
  102. nint charArray = objc_msgSend (ptr, _utf8Register);
  103. return Marshal.PtrToStringAnsi (charArray);
  104. }
  105. protected override void SetClipboardDataImpl (string text)
  106. {
  107. nint str = default;
  108. try
  109. {
  110. str = objc_msgSend (objc_msgSend (_nsString, _allocRegister), _initWithUtf8Register, text);
  111. objc_msgSend (_generalPasteboard, _clearContentsRegister);
  112. objc_msgSend (_generalPasteboard, _setStringRegister, str, _utfTextType);
  113. }
  114. finally
  115. {
  116. if (str != default (nint))
  117. {
  118. objc_msgSend (str, sel_registerName ("release"));
  119. }
  120. }
  121. }
  122. private bool CheckSupport ()
  123. {
  124. (int exitCode, string result) = ClipboardProcessRunner.Bash ("which pbcopy", waitForOutput: true);
  125. if (exitCode != 0 || !result.FileExists ())
  126. {
  127. return false;
  128. }
  129. (exitCode, result) = ClipboardProcessRunner.Bash ("which pbpaste", waitForOutput: true);
  130. return exitCode == 0 && result.FileExists ();
  131. }
  132. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  133. private static extern nint objc_getClass (string className);
  134. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  135. private static extern nint objc_msgSend (nint receiver, nint selector);
  136. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  137. private static extern nint objc_msgSend (nint receiver, nint selector, string arg1);
  138. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  139. private static extern nint objc_msgSend (nint receiver, nint selector, nint arg1);
  140. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  141. private static extern nint objc_msgSend (nint receiver, nint selector, nint arg1, nint arg2);
  142. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  143. private static extern nint sel_registerName (string selectorName);
  144. }
  145. /// <summary>
  146. /// A clipboard implementation for Linux, when running under WSL. This implementation uses the Windows clipboard
  147. /// to store the data, and uses Windows' powershell.exe (launched via WSL interop services) to set/get the Windows
  148. /// clipboard.
  149. /// </summary>
  150. internal class WSLClipboard : ClipboardBase
  151. {
  152. private static string _powershellPath = string.Empty;
  153. public override bool IsSupported => CheckSupport ();
  154. protected override string GetClipboardDataImpl ()
  155. {
  156. if (!IsSupported)
  157. {
  158. return string.Empty;
  159. }
  160. (int exitCode, string output) =
  161. ClipboardProcessRunner.Process (_powershellPath, "-noprofile -command \"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Get-Clipboard\"");
  162. if (exitCode == 0)
  163. {
  164. if (output.EndsWith ("\r\n"))
  165. {
  166. output = output.Substring (0, output.Length - 2);
  167. }
  168. return output;
  169. }
  170. return string.Empty;
  171. }
  172. protected override void SetClipboardDataImpl (string text)
  173. {
  174. if (!IsSupported)
  175. {
  176. return;
  177. }
  178. (int exitCode, string output) = ClipboardProcessRunner.Process (
  179. _powershellPath,
  180. $"-noprofile -command \"Set-Clipboard -Value \\\"{text}\\\"\""
  181. );
  182. }
  183. private bool CheckSupport ()
  184. {
  185. if (string.IsNullOrEmpty (_powershellPath))
  186. {
  187. // Specify pwsh.exe (not pwsh) to ensure we get the Windows version (invoked via WSL)
  188. (int exitCode, string result) = ClipboardProcessRunner.Bash ("which pwsh.exe", waitForOutput: true);
  189. if (exitCode > 0)
  190. {
  191. (exitCode, result) = ClipboardProcessRunner.Bash ("which powershell.exe", waitForOutput: true);
  192. }
  193. if (exitCode == 0)
  194. {
  195. _powershellPath = result;
  196. }
  197. }
  198. return !string.IsNullOrEmpty (_powershellPath);
  199. }
  200. }