using NStack;
using System;
namespace Terminal.Gui {
///
/// Provides cut, copy, and paste support for the OS clipboard.
///
///
///
/// On Windows, the class uses the Windows Clipboard APIs via P/Invoke.
///
///
/// On Linux, when not running under Windows Subsystem for Linux (WSL),
/// the class uses the xclip command line tool. If xclip is not installed,
/// the clipboard will not work.
///
///
/// On Linux, when running under Windows Subsystem for Linux (WSL),
/// the class launches Windows' powershell.exe via WSL interop and uses the
/// "Set-Clipboard" and "Get-Clipboard" Powershell CmdLets.
///
///
/// On the Mac, the class uses the MacO OS X pbcopy and pbpaste command line tools
/// and the Mac clipboard APIs vai P/Invoke.
///
///
public static class Clipboard {
static ustring contents;
///
/// Gets (copies from) or sets (pastes to) the contents of the OS clipboard.
///
public static ustring Contents {
get {
try {
if (IsSupported) {
return contents = ustring.Make (Application.Driver.Clipboard.GetClipboardData ());
} else {
return contents;
}
} catch (Exception) {
return contents;
}
}
set {
try {
if (IsSupported) {
if (value == null) {
value = string.Empty;
}
Application.Driver.Clipboard.SetClipboardData (value.ToString ());
}
contents = value;
} catch (NotSupportedException e) {
throw e;
} catch (Exception) {
contents = value;
}
}
}
///
/// Returns true if the environmental dependencies are in place to interact with the OS clipboard.
///
///
///
public static bool IsSupported { get => Application.Driver.Clipboard.IsSupported; }
///
/// Copies the contents of the OS clipboard to if possible.
///
/// The contents of the OS clipboard if successful, if not.
/// the OS clipboard was retrieved, otherwise.
public static bool TryGetClipboardData (out string result)
{
if (IsSupported && Application.Driver.Clipboard.TryGetClipboardData (out result)) {
if (contents != result) {
contents = result;
}
return true;
}
result = string.Empty;
return false;
}
///
/// Pastes the to the OS clipboard if possible.
///
/// The text to paste to the OS clipboard.
/// the OS clipboard was set, otherwise.
public static bool TrySetClipboardData (string text)
{
if (IsSupported && Application.Driver.Clipboard.TrySetClipboardData (text)) {
contents = text;
return true;
}
return false;
}
}
}