| 1 | using System.Security.Cryptography; |
| 2 | using System.Text.Json.Nodes; |
| 3 | using System.Windows.Automation; |
| 4 | |
| 5 | namespace Cage.GuestClipboard; |
| 6 | |
| 7 | |
| 8 | |
| 9 | internal static class WindowsIme |
| 10 | { |
| 11 | private sealed record Focus(string Context, double[] Rect, bool Password); |
| 12 | private sealed record Composition(string ID, string Context, int Sequence, DateTime Updated); |
| 13 | private static readonly SemaphoreSlim Probes = new(1, 1); |
| 14 | private static Composition? composition; |
| 15 | |
| 16 | private static Focus? Probe(int process, string windowTarget, double x, double y) |
| 17 | { |
| 18 | var element = AutomationElement.FocusedElement; |
| 19 | if (element is null || element.Current.ProcessId != process || !element.Current.IsEnabled || element.Current.IsOffscreen) |
| 20 | return null; |
| 21 | bool editable = element.TryGetCurrentPattern(ValuePattern.Pattern, out var value) && !((ValuePattern)value).Current.IsReadOnly; |
| 22 | if (!editable && element.TryGetCurrentPattern(TextPattern.Pattern, out var text)) |
| 23 | { |
| 24 | var readOnly = ((TextPattern)text).DocumentRange.GetAttributeValue(TextPattern.IsReadOnlyAttribute); |
| 25 | editable = readOnly is bool b && !b; |
| 26 | } |
| 27 | if (!editable) return null; |
| 28 | var bounds = element.Current.BoundingRectangle; |
| 29 | var rect = new double[] { bounds.X-x, bounds.Y-y, Math.Max(1,bounds.Width), Math.Max(1,bounds.Height) }; |
| 30 | if (element.TryGetCurrentPattern(TextPattern.Pattern, out var caret)) |
| 31 | { |
| 32 | var ranges = ((TextPattern)caret).GetSelection(); |
| 33 | var geometry = ranges.Length == 1 ? ranges[0].GetBoundingRectangles() : []; |
| 34 | if (geometry.Length != 0) rect = [geometry[0].X-x,geometry[0].Y-y,Math.Max(1,geometry[0].Width),Math.Max(1,geometry[0].Height)]; |
| 35 | } |
| 36 | var identity = windowTarget + ":" + string.Join(',',element.GetRuntimeId()); |
| 37 | var context = Convert.ToHexString(SHA256.HashData(Protocol.Utf8.GetBytes(identity)).AsSpan(0,16)).ToLowerInvariant(); |
| 38 | return new Focus(context,rect,element.Current.IsPassword); |
| 39 | } |
| 40 | |
| 41 | internal static async Task RequirePhoneFocus(JsonObject input, int process, string windowTarget, CancellationToken token) |
| 42 | { |
| 43 | if (!input.ContainsKey("phone_focus")) return; |
| 44 | var requested = input["phone_focus"]?.GetValue<string>() ?? ""; |
| 45 | var focus = await Handle(new JsonObject { ["mode"] = "status" }, process, windowTarget, 0, 0, |
| 46 | _ => throw new InvalidDataException("desktop_phone_focus_changed"), token); |
| 47 | if (requested.Length == 0 || focus["available"]?.GetValue<bool>() != true || |
| 48 | focus["password"]?.GetValue<bool>() == true || focus["context"]?.GetValue<string>() != requested) |
| 49 | throw new InvalidDataException("desktop_phone_focus_changed"); |
| 50 | } |
| 51 | |
| 52 | internal static async Task<JsonObject> Handle(JsonObject input, int process, string windowTarget, double x, double y, Action<string> commit, CancellationToken token) |
| 53 | { |
| 54 | var mode = input["mode"]?.GetValue<string>() ?? ""; |
| 55 | var id = input["session"]?.GetValue<string>() ?? ""; |
| 56 | var sequence = input["sequence"]?.GetValue<int>() ?? 0; |
| 57 | if (mode is not ("status" or "begin" or "update" or "commit" or "cancel")) throw new InvalidDataException("input_mode_invalid"); |
| 58 | if (mode != "status" && (id.Length != 32 || id.Any(c => !char.IsAsciiHexDigit(c)) || sequence < 0)) throw new InvalidDataException("input_session_invalid"); |
| 59 | if (mode == "cancel") |
| 60 | { |
| 61 | if (composition?.ID == id && sequence > composition.Sequence) composition = null; |
| 62 | return new JsonObject { ["available"] = false }; |
| 63 | } |
| 64 | if (!await Probes.WaitAsync(0,token)) return new JsonObject { ["available"] = false }; |
| 65 | var probe = Task.Run(() => { try { return Probe(process,windowTarget,x,y); } finally { Probes.Release(); } }); |
| 66 | Focus? focus; |
| 67 | try { focus = await probe.WaitAsync(TimeSpan.FromSeconds(2),token); } |
| 68 | catch (Exception e) when (e is not OperationCanceledException) { return new JsonObject { ["available"] = false }; } |
| 69 | if (focus is null || !SessionGuard.Available()) { composition = null; return new JsonObject { ["available"] = false }; } |
| 70 | if (composition is not null && (composition.Context != focus.Context || DateTime.UtcNow-composition.Updated > TimeSpan.FromSeconds(30))) composition = null; |
| 71 | JsonObject Snapshot() => new() { ["available"] = true, ["context"] = focus.Context, ["rect"] = new JsonArray(focus.Rect.Select(v => (JsonNode?)JsonValue.Create(v)).ToArray()), ["preedit_supported"] = false, ["password"] = focus.Password }; |
| 72 | if (mode == "status") { if (composition?.ID == id) composition = composition with { Updated = DateTime.UtcNow }; return Snapshot(); } |
| 73 | if (mode == "begin") |
| 74 | { |
| 75 | if (input["context"]?.GetValue<string>() != focus.Context) return new JsonObject { ["available"] = false }; |
| 76 | composition = new Composition(id,focus.Context,sequence,DateTime.UtcNow); return Snapshot(); |
| 77 | } |
| 78 | if (composition?.ID != id || sequence <= composition.Sequence) return new JsonObject { ["available"] = false }; |
| 79 | var content = input["text"]?.GetValue<string>() ?? ""; |
| 80 | if (Protocol.Utf8.GetByteCount(content) > 8192) throw new InvalidDataException("input_text_limit"); |
| 81 | if (mode == "commit") { commit(content); composition = null; } |
| 82 | else composition = composition with { Sequence = sequence, Updated = DateTime.UtcNow }; |
| 83 | return Snapshot(); |
| 84 | } |
| 85 | } |