using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("TextCopy")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2022. All rights reserved")]
[assembly: AssemblyDescription("A cross platform package to copy text to the clipboard.")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("6.2.1+409eda72dd615c1ff2cd7327d5a294553eaa9b81")]
[assembly: AssemblyProduct("TextCopy")]
[assembly: AssemblyTitle("TextCopy")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/CopyText/TextCopy.git")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Microsoft.CodeAnalysis.Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Microsoft.CodeAnalysis.Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
internal sealed class NullableAttribute : Attribute
{
public readonly byte[] NullableFlags;
public NullableAttribute(byte P_0)
{
NullableFlags = new byte[1] { P_0 };
}
public NullableAttribute(byte[] P_0)
{
NullableFlags = P_0;
}
}
[CompilerGenerated]
[Microsoft.CodeAnalysis.Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
internal sealed class NullableContextAttribute : Attribute
{
public readonly byte Flag;
public NullableContextAttribute(byte P_0)
{
Flag = P_0;
}
}
}
internal static class BashRunner
{
public static string Run(string commandLine)
{
StringBuilder errorBuilder = new StringBuilder();
StringBuilder outputBuilder = new StringBuilder();
string text = "-c \"" + commandLine + "\"";
using Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "bash",
Arguments = text,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = false
}
};
process.Start();
process.OutputDataReceived += delegate(object _, DataReceivedEventArgs args)
{
outputBuilder.AppendLine(args.Data);
};
process.BeginOutputReadLine();
process.ErrorDataReceived += delegate(object _, DataReceivedEventArgs args)
{
errorBuilder.AppendLine(args.Data);
};
process.BeginErrorReadLine();
if (!process.DoubleWaitForExit())
{
string message = $"Process timed out. Command line: bash {text}.\nOutput: {outputBuilder}\nError: {errorBuilder}";
throw new Exception(message);
}
if (process.ExitCode == 0)
{
return outputBuilder.ToString();
}
string message2 = $"Could not execute process. Command line: bash {text}.\nOutput: {outputBuilder}\nError: {errorBuilder}";
throw new Exception(message2);
}
private static bool DoubleWaitForExit(this Process process)
{
bool flag = process.WaitForExit(500);
if (flag)
{
process.WaitForExit();
}
return flag;
}
}
internal static class LinuxClipboard
{
private static bool isWsl;
static LinuxClipboard()
{
isWsl = Environment.GetEnvironmentVariable("WSL_DISTRO_NAME") != null;
}
public static async Task SetTextAsync(string text, CancellationToken cancellation)
{
string tempFileName = Path.GetTempFileName();
await File.WriteAllTextAsync(tempFileName, text, cancellation);
if (!cancellation.IsCancellationRequested)
{
InnerSetText(tempFileName);
}
}
public static void SetText(string text)
{
string tempFileName = Path.GetTempFileName();
File.WriteAllText(tempFileName, text);
InnerSetText(tempFileName);
}
private static void InnerSetText(string tempFileName)
{
try
{
if (isWsl)
{
BashRunner.Run("cat " + tempFileName + " | clip.exe ");
}
else
{
BashRunner.Run("cat " + tempFileName + " | xsel -i --clipboard ");
}
}
finally
{
File.Delete(tempFileName);
}
}
public static string? GetText()
{
string tempFileName = Path.GetTempFileName();
try
{
InnerGetText(tempFileName);
return File.ReadAllText(tempFileName);
}
finally
{
File.Delete(tempFileName);
}
}
public static async Task<string?> GetTextAsync(CancellationToken cancellation)
{
string tempFileName = Path.GetTempFileName();
try
{
InnerGetText(tempFileName);
return await File.ReadAllTextAsync(tempFileName, cancellation);
}
finally
{
File.Delete(tempFileName);
}
}
private static void InnerGetText(string tempFileName)
{
if (isWsl)
{
BashRunner.Run("powershell.exe -NoProfile Get-Clipboard > " + tempFileName);
}
else
{
BashRunner.Run("xsel -o --clipboard > " + tempFileName);
}
}
}
internal static class OsxClipboard
{
private static IntPtr nsString;
private static IntPtr nsPasteboard;
private static IntPtr nsStringPboardType;
private static IntPtr utfTextType;
private static IntPtr generalPasteboard;
private static IntPtr initWithUtf8Register;
private static IntPtr allocRegister;
private static IntPtr setStringRegister;
private static IntPtr stringForTypeRegister;
private static IntPtr utf8Register;
private static IntPtr generalPasteboardRegister;
private static IntPtr clearContentsRegister;
static OsxClipboard()
{
nsString = objc_getClass("NSString");
nsPasteboard = objc_getClass("NSPasteboard");
initWithUtf8Register = sel_registerName("initWithUTF8String:");
allocRegister = sel_registerName("alloc");
setStringRegister = sel_registerName("setString:forType:");
stringForTypeRegister = sel_registerName("stringForType:");
utf8Register = sel_registerName("UTF8String");
generalPasteboardRegister = sel_registerName("generalPasteboard");
clearContentsRegister = sel_registerName("clearContents");
utfTextType = objc_msgSend(objc_msgSend(nsString, allocRegister), initWithUtf8Register, "public.utf8-plain-text");
nsStringPboardType = objc_msgSend(objc_msgSend(nsString, allocRegister), initWithUtf8Register, "NSStringPboardType");
generalPasteboard = objc_msgSend(nsPasteboard, generalPasteboardRegister);
}
public static string? GetText()
{
IntPtr receiver = objc_msgSend(generalPasteboard, stringForTypeRegister, nsStringPboardType);
IntPtr ptr = objc_msgSend(receiver, utf8Register);
return Marshal.PtrToStringAnsi(ptr);
}
public static Task<string?> GetTextAsync(CancellationToken cancellation)
{
return Task.FromResult(GetText());
}
public static void SetText(string text)
{
IntPtr intPtr = default(IntPtr);
try
{
intPtr = objc_msgSend(objc_msgSend(nsString, allocRegister), initWithUtf8Register, text);
objc_msgSend(generalPasteboard, clearContentsRegister);
objc_msgSend(generalPasteboard, setStringRegister, intPtr, utfTextType);
}
finally
{
if (intPtr != (IntPtr)0)
{
objc_msgSend(intPtr, sel_registerName("release"));
}
}
}
public static Task SetTextAsync(string text, CancellationToken cancellation)
{
SetText(text);
return Task.CompletedTask;
}
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
private static extern IntPtr objc_getClass(string className);
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
private static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector);
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
private static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector, string arg1);
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
private static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector, IntPtr arg1);
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
private static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector, IntPtr arg1, IntPtr arg2);
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
private static extern IntPtr sel_registerName(string selectorName);
}
internal static class WindowsClipboard
{
private const uint cfUnicodeText = 13u;
public static async Task SetTextAsync(string text, CancellationToken cancellation)
{
await TryOpenClipboardAsync(cancellation);
InnerSet(text);
}
public static void SetText(string text)
{
TryOpenClipboard();
InnerSet(text);
}
private static void InnerSet(string text)
{
EmptyClipboard();
IntPtr intPtr = default(IntPtr);
try
{
int cb = (text.Length + 1) * 2;
intPtr = Marshal.AllocHGlobal(cb);
if (intPtr == (IntPtr)0)
{
ThrowWin32();
}
IntPtr intPtr2 = GlobalLock(intPtr);
if (intPtr2 == (IntPtr)0)
{
ThrowWin32();
}
try
{
Marshal.Copy(text.ToCharArray(), 0, intPtr2, text.Length);
}
finally
{
GlobalUnlock(intPtr2);
}
if (SetClipboardData(13u, intPtr) == (IntPtr)0)
{
ThrowWin32();
}
intPtr = default(IntPtr);
}
finally
{
if (intPtr != (IntPtr)0)
{
Marshal.FreeHGlobal(intPtr);
}
CloseClipboard();
}
}
private static async Task TryOpenClipboardAsync(CancellationToken cancellation)
{
int num = 10;
while (!OpenClipboard((IntPtr)0))
{
int num2 = num - 1;
num = num2;
if (num2 == 0)
{
ThrowWin32();
}
await Task.Delay(100, cancellation);
}
}
private static void TryOpenClipboard()
{
int num = 10;
while (!OpenClipboard((IntPtr)0))
{
if (--num == 0)
{
ThrowWin32();
}
Thread.Sleep(100);
}
}
public static async Task<string?> GetTextAsync(CancellationToken cancellation)
{
if (!IsClipboardFormatAvailable(13u))
{
return null;
}
await TryOpenClipboardAsync(cancellation);
return InnerGet();
}
public static string? GetText()
{
if (!IsClipboardFormatAvailable(13u))
{
return null;
}
TryOpenClipboard();
return InnerGet();
}
private static string? InnerGet()
{
IntPtr intPtr = default(IntPtr);
IntPtr intPtr2 = default(IntPtr);
try
{
intPtr = GetClipboardData(13u);
if (intPtr == (IntPtr)0)
{
return null;
}
intPtr2 = GlobalLock(intPtr);
if (intPtr2 == (IntPtr)0)
{
return null;
}
int num = GlobalSize(intPtr);
byte[] array = new byte[num];
Marshal.Copy(intPtr2, array, 0, num);
return Encoding.Unicode.GetString(array).TrimEnd('\0');
}
finally
{
if (intPtr2 != (IntPtr)0)
{
GlobalUnlock(intPtr);
}
CloseClipboard();
}
}
private static void ThrowWin32()
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsClipboardFormatAvailable(uint format);
[DllImport("User32.dll", SetLastError = true)]
private static extern IntPtr GetClipboardData(uint uFormat);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GlobalLock(IntPtr hMem);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GlobalUnlock(IntPtr hMem);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseClipboard();
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetClipboardData(uint uFormat, IntPtr data);
[DllImport("user32.dll")]
private static extern bool EmptyClipboard();
[DllImport("Kernel32.dll", SetLastError = true)]
private static extern int GlobalSize(IntPtr hMem);
}
namespace TextCopy
{
public class BlazorClipboard : IClipboard
{
private static Type[] types = new Type[2]
{
typeof(string),
typeof(object[])
};
private object jsRuntime;
private MethodInfo invokeAsync;
public BlazorClipboard(object jsRuntime)
{
this.jsRuntime = jsRuntime;
Type type = jsRuntime.GetType();
MethodInfo method = type.GetMethod("InvokeAsync", types);
if (method == null)
{
IEnumerable<string> values = from x in type.GetMethods()
select x.ToString();
throw new Exception($"Unable to find InvokeAsync on {type.FullName}. Methods:{Environment.NewLine}{string.Join(Environment.NewLine, values)}");
}
invokeAsync = method.MakeGenericMethod(typeof(string));
}
public virtual async Task<string?> GetTextAsync(CancellationToken cancellation = default(CancellationToken))
{
object[] parameters = new object[2]
{
"navigator.clipboard.readText",
Array.Empty<object>()
};
return await (ValueTask<string>)invokeAsync.Invoke(jsRuntime, parameters);
}
public virtual string? GetText()
{
return GetTextAsync().GetAwaiter().GetResult();
}
public virtual async Task SetTextAsync(string text, CancellationToken cancellation = default(CancellationToken))
{
object[] parameters = new object[2]
{
"navigator.clipboard.writeText",
new object[1] { text }
};
await (ValueTask<string>)invokeAsync.Invoke(jsRuntime, parameters);
}
public virtual void SetText(string text)
{
SetTextAsync(text).GetAwaiter().GetResult();
}
}
public class Clipboard : IClipboard
{
public virtual Task<string?> GetTextAsync(CancellationToken cancellation = default(CancellationToken))
{
return ClipboardService.GetTextAsync(cancellation);
}
public virtual string? GetText()
{
return ClipboardService.GetText();
}
public virtual Task SetTextAsync(string text, CancellationToken cancellation = default(CancellationToken))
{
return ClipboardService.SetTextAsync(text, cancellation);
}
public virtual void SetText(string text)
{
ClipboardService.SetText(text);
}
}
public static class ClipboardService
{
private static Func<CancellationToken, Task<string?>> getAsyncFunc;
private static Func<string?> getFunc;
private static Func<string, CancellationToken, Task> setAsyncAction;
private static Action<string> setAction;
public static Task<string?> GetTextAsync(CancellationToken cancellation = default(CancellationToken))
{
return getAsyncFunc(cancellation);
}
public static string? GetText()
{
return getFunc();
}
static ClipboardService()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("Browser")))
{
throw new Exception("The static class ClipboardService is not supported on Blazor. Instead inject an IClipboard using ServiceExtensionsInjectClipboard.");
}
getAsyncFunc = CreateAsyncGet();
getFunc = CreateGet();
setAsyncAction = CreateAsyncSet();
setAction = CreateSet();
}
public static Task SetTextAsync(string text, CancellationToken cancellation = default(CancellationToken))
{
return setAsyncAction(text, cancellation);
}
public static void SetText(string text)
{
setAction(text);
}
private static Func<CancellationToken, Task<string?>> CreateAsyncGet()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return WindowsClipboard.GetTextAsync;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return OsxClipboard.GetTextAsync;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return LinuxClipboard.GetTextAsync;
}
throw new NotSupportedException();
}
private static Func<string?> CreateGet()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return WindowsClipboard.GetText;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return OsxClipboard.GetText;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return LinuxClipboard.GetText;
}
throw new NotSupportedException();
}
private static Func<string, CancellationToken, Task> CreateAsyncSet()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return WindowsClipboard.SetTextAsync;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return OsxClipboard.SetTextAsync;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return LinuxClipboard.SetTextAsync;
}
return delegate
{
throw new NotSupportedException();
};
}
private static Action<string> CreateSet()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return WindowsClipboard.SetText;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return OsxClipboard.SetText;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return LinuxClipboard.SetText;
}
return delegate
{
throw new NotSupportedException();
};
}
}
public interface IClipboard
{
Task<string?> GetTextAsync(CancellationToken cancellation = default(CancellationToken));
string? GetText();
Task SetTextAsync(string text, CancellationToken cancellation = default(CancellationToken));
void SetText(string text);
}
public class MockClipboard : IClipboard
{
public virtual Task<string?> GetTextAsync(CancellationToken cancellation = default(CancellationToken))
{
return Task.FromResult<string>(null);
}
public virtual string? GetText()
{
return null;
}
public virtual Task SetTextAsync(string text, CancellationToken cancellation = default(CancellationToken))
{
return Task.CompletedTask;
}
public void SetText(string text)
{
}
}
public static class ServiceExtensions
{
public static void InjectMockClipboard(this IServiceCollection services)
{
services.AddSingleton((Func<IServiceProvider, IClipboard>)((IServiceProvider _) => new MockClipboard()));
}
public static void InjectClipboard(this IServiceCollection services)
{
services.AddSingleton((Func<IServiceProvider, IClipboard>)delegate(IServiceProvider provider)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("Browser")))
{
Type type = Type.GetType("Microsoft.JSInterop.IJSRuntime, Microsoft.JSInterop", throwOnError: false);
if (type == null)
{
throw new Exception("Running in Blazor but could not resolve JSInterop type.");
}
object service = provider.GetService(type);
if (service == null)
{
throw new Exception("Running in Blazor but could not get the JSInterop instance from the IServiceProvider.");
}
return new BlazorClipboard(service);
}
return new Clipboard();
});
}
}
}
internal class TextCopy_ProcessedByFody
{
internal const string FodyVersion = "6.6.4.0";
internal const string Weavers = "1.0.0";
}