ClipboardImpl.cs 9.0 KB

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