using System.Text.Json.Nodes;
using Windows.ApplicationModel.DataTransfer;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Controls;
namespace XFEWorkflow.Services;
public sealed class ScreenToolsService
{
private readonly SemaphoreSlim selectionGate = new(1);
private readonly object selectionSync = new();
private CancellationTokenSource? activeSelection;
public void CancelSelection() { lock (selectionSync) activeSelection?.Cancel(); }
public async ValueTask<JsonObject> InvokeAsync(string method, JsonObject input, CancellationToken ct)
{
if (method is "screen.selectRegion" or "screen.selectTemplate")
{
await selectionGate.WaitAsync(ct);
using var selection = CancellationTokenSource.CreateLinkedTokenSource(ct);
lock (selectionSync) activeSelection = selection;
try
{
return await OnUIAsync(async () =>
{
if (method == "screen.selectTemplate")
{
var template = await ScreenRegionPicker.PickTemplateAsync(selection.Token) ?? throw new OperationCanceledException("已取消模板框选。");
return new JsonObject { ["templatePath"] = template.Value, ["width"] = template.Width, ["height"] = template.Height };
}
var selected = input.String("imagePath") is { Length: > 0 } path
? await ScreenRegionPicker.PickImageAsync(path, selection.Token)
: await ScreenRegionPicker.PickAsync(input.Boolean("hideWorkflow", true), selection.Token, input.Boolean("pointMode"));
var region = selected ?? throw new OperationCanceledException("已取消区域框选。");
return new JsonObject { ["region"] = region.ToJson(), ["point"] = new JsonObject { ["x"] = region.CenterX, ["y"] = region.CenterY } };
}, selection.Token);
}
finally { lock (selectionSync) activeSelection = null; selectionGate.Release(); }
}
return await OnUIAsync(async () =>
{
ct.ThrowIfCancellationRequested();
if (method == "screen.clipboardRead")
{
var data = Clipboard.GetContent(); var text = data.Contains(StandardDataFormats.Text) ? await data.GetTextAsync().AsTask(ct) : "";
return new JsonObject { ["text"] = text };
}
if (method == "screen.clipboardWrite")
{
var data = new DataPackage(); data.SetText(input.String("text")); Clipboard.SetContent(data); Clipboard.Flush(); return new JsonObject();
}
throw new NotSupportedException(method);
}, ct);
}
private static Task<T> OnUIAsync<T>(Func<Task<T>> operation, CancellationToken ct)
{
var result = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
async void Execute()
{
try { ct.ThrowIfCancellationRequested(); result.TrySetResult(await operation()); }
catch (OperationCanceledException ex) { if (ct.IsCancellationRequested) result.TrySetCanceled(ct); else result.TrySetException(ex); }
catch (Exception ex) { result.TrySetException(ex); }
}
var dispatcher = App.MainWindow.DispatcherQueue;
if (dispatcher.HasThreadAccess) Execute(); else if (!dispatcher.TryEnqueue(Execute)) result.TrySetException(new IOException("界面调度器已关闭。"));
return result.Task;
}
}
using System.Text.Json.Nodes;
using Windows.ApplicationModel.DataTransfer;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Controls;
namespace XFEWorkflow.Services;
public sealed class ScreenToolsService
{
private readonly SemaphoreSlim selectionGate = new(1);
private readonly object selectionSync = new();
private CancellationTokenSource? activeSelection;
public void CancelSelection() { lock (selectionSync) activeSelection?.Cancel(); }
public async ValueTask<JsonObject> InvokeAsync(string method, JsonObject input, CancellationToken ct)
{
if (method is "screen.selectRegion" or "screen.selectTemplate")
{
await selectionGate.WaitAsync(ct);
using var selection = CancellationTokenSource.CreateLinkedTokenSource(ct);
lock (selectionSync) activeSelection = selection;
try
{
return await OnUIAsync(async () =>
{
if (method == "screen.selectTemplate")
{
var template = await ScreenRegionPicker.PickTemplateAsync(selection.Token) ?? throw new OperationCanceledException("已取消模板框选。");
return new JsonObject { ["templatePath"] = template.Value, ["width"] = template.Width, ["height"] = template.Height };
}
var selected = input.String("imagePath") is { Length: > 0 } path
? await ScreenRegionPicker.PickImageAsync(path, selection.Token)
: await ScreenRegionPicker.PickAsync(input.Boolean("hideWorkflow", true), selection.Token, input.Boolean("pointMode"));
var region = selected ?? throw new OperationCanceledException("已取消区域框选。");
return new JsonObject { ["region"] = region.ToJson(), ["point"] = new JsonObject { ["x"] = region.CenterX, ["y"] = region.CenterY } };
}, selection.Token);
}
finally { lock (selectionSync) activeSelection = null; selectionGate.Release(); }
}
return await OnUIAsync(async () =>
{
ct.ThrowIfCancellationRequested();
if (method == "screen.clipboardRead")
{
var data = Clipboard.GetContent(); var text = data.Contains(StandardDataFormats.Text) ? await data.GetTextAsync().AsTask(ct) : "";
return new JsonObject { ["text"] = text };
}
if (method == "screen.clipboardWrite")
{
var data = new DataPackage(); data.SetText(input.String("text")); Clipboard.SetContent(data); Clipboard.Flush(); return new JsonObject();
}
throw new NotSupportedException(method);
}, ct);
}
private static Task<T> OnUIAsync<T>(Func<Task<T>> operation, CancellationToken ct)
{
var result = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
async void Execute()
{
try { ct.ThrowIfCancellationRequested(); result.TrySetResult(await operation()); }
catch (OperationCanceledException ex) { if (ct.IsCancellationRequested) result.TrySetCanceled(ct); else result.TrySetException(ex); }
catch (Exception ex) { result.TrySetException(ex); }
}
var dispatcher = App.MainWindow.DispatcherQueue;
if (dispatcher.HasThreadAccess) Execute(); else if (!dispatcher.TryEnqueue(Execute)) result.TrySetException(new IOException("界面调度器已关闭。"));
return result.Task;
}
}