1
0
Files
Toak/IO/TextInjector.cs

105 lines
3.5 KiB
C#

using System.Diagnostics;
using Toak.Core;
namespace Toak.IO;
public static class TextInjector
{
public static void Inject(string text, string backend)
{
Logger.LogDebug($"Injecting text: '{text}' with {backend}");
if (string.IsNullOrWhiteSpace(text)) return;
try
{
ProcessStartInfo pInfo;
if (backend.ToLowerInvariant() == "wtype")
{
Logger.LogDebug($"Injecting text using wtype...");
pInfo = new ProcessStartInfo
{
FileName = "wtype",
Arguments = $"\"{text.Replace("\"", "\\\"")}\"",
UseShellExecute = false,
CreateNoWindow = true
};
}
else // xdotool
{
Logger.LogDebug($"Injecting text using xdotool...");
pInfo = new ProcessStartInfo
{
FileName = "xdotool",
Arguments = $"type --clearmodifiers --delay 0 \"{text.Replace("\"", "\\\"")}\"",
UseShellExecute = false,
CreateNoWindow = true
};
}
var process = Process.Start(pInfo);
process?.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine($"[TextInjector] Error injecting text: {ex.Message}");
Notifications.Notify("Injection Error", "Could not type text into window.");
}
}
public static async Task<string> InjectStreamAsync(IAsyncEnumerable<string> tokenStream, string backend)
{
string fullText = string.Empty;
try
{
ProcessStartInfo pInfo;
if (backend.ToLowerInvariant() == "wtype")
{
Logger.LogDebug($"Setting up stream injection using wtype...");
pInfo = new ProcessStartInfo
{
FileName = "wtype",
Arguments = "-",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true
};
}
else // xdotool
{
Logger.LogDebug($"Setting up stream injection using xdotool...");
pInfo = new ProcessStartInfo
{
FileName = "xdotool",
Arguments = "type --clearmodifiers --delay 0 --file -",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true
};
}
using var process = Process.Start(pInfo);
if (process == null) return string.Empty;
Logger.LogDebug("Started stream injection process, waiting for tokens...");
await foreach (var token in tokenStream)
{
Logger.LogDebug($"Injecting token: '{token}'");
fullText += token;
await process.StandardInput.WriteAsync(token);
await process.StandardInput.FlushAsync();
}
Logger.LogDebug("Stream injection complete. Closing standard input.");
process.StandardInput.Close();
await process.WaitForExitAsync();
}
catch (Exception ex)
{
Console.WriteLine($"[TextInjector] Error injecting text stream: {ex.Message}");
Notifications.Notify("Injection Error", "Could not type text stream into window.");
}
return fullText;
}
}