| 1 | using System.Runtime.InteropServices; |
| 2 | using System.Text; |
| 3 | using System.Text.Json; |
| 4 | |
| 5 | namespace Cage.Windows; |
| 6 | |
| 7 | |
| 8 | |
| 9 | internal sealed class NativeInput : TextBox |
| 10 | { |
| 11 | private readonly Action<Dictionary<string, object?>> publish; |
| 12 | private string owner = ""; |
| 13 | private bool composing, resetting; |
| 14 | private Keys lastKey; |
| 15 | private bool repeating; |
| 16 | private int scanCode; |
| 17 | private bool extendedKey; |
| 18 | private char? highSurrogate; |
| 19 | |
| 20 | internal NativeInput(Action<Dictionary<string, object?>> publish) |
| 21 | { |
| 22 | this.publish = publish; |
| 23 | BorderStyle = BorderStyle.None; Multiline = true; TabStop = false; |
| 24 | ImeMode = ImeMode.On; Visible = false; Size = new Size(1, 24); |
| 25 | LostFocus += (_, _) => { |
| 26 | Cancel(); Emit("deactivated"); owner = ""; Visible = false; |
| 27 | }; |
| 28 | } |
| 29 | |
| 30 | private void Emit(string kind, string? text = null, int start = 0, int end = 0) |
| 31 | { |
| 32 | if (owner.Length == 0) return; |
| 33 | publish(new() { ["owner"] = owner, ["kind"] = kind, ["text"] = text, |
| 34 | ["selectionStart"] = start, ["selectionEnd"] = end }); |
| 35 | } |
| 36 | |
| 37 | internal bool ProcessRequest(JsonElement value, Control web, double zoom) |
| 38 | { |
| 39 | var requestedOwner = value.Text("owner"); |
| 40 | if (!Guid.TryParse(requestedOwner, out _)) return false; |
| 41 | var operation = value.Text("operation"); |
| 42 | if (operation == "activate") |
| 43 | { |
| 44 | if (owner != requestedOwner) { Cancel(); owner = requestedOwner; } |
| 45 | Visible = true; BringToFront(); |
| 46 | } |
| 47 | else if (owner != requestedOwner) return false; |
| 48 | if (operation is "activate" or "caret") |
| 49 | { |
| 50 | if (!value.TryGetProperty("x", out var vx) || !vx.TryGetDouble(out var x) || |
| 51 | !value.TryGetProperty("y", out var vy) || !vy.TryGetDouble(out var y) || |
| 52 | !value.TryGetProperty("height", out var vh) || !vh.TryGetDouble(out var height) || |
| 53 | !double.IsFinite(x) || !double.IsFinite(y) || !double.IsFinite(height) || |
| 54 | Math.Abs(x) > 32768 || Math.Abs(y) > 32768 || height <= 0 || height > 4096) return false; |
| 55 | var scale = web.DeviceDpi / 96.0 * zoom; |
| 56 | var point = Parent!.PointToClient(web.PointToScreen(new Point((int)(x * scale), (int)(y * scale)))); |
| 57 | Bounds = new Rectangle(point, new Size(1, Math.Max(1, (int)(height * scale)))); |
| 58 | if (operation == "activate") Focus(); |
| 59 | PositionCandidates(); |
| 60 | } |
| 61 | else if (operation == "cancel") Cancel(); |
| 62 | else if (operation == "deactivate") { Cancel(); owner = ""; Visible = false; web.Focus(); } |
| 63 | else return false; |
| 64 | return true; |
| 65 | } |
| 66 | |
| 67 | private void Cancel() |
| 68 | { |
| 69 | if (composing) Emit("compositionend", ""); |
| 70 | composing = false; resetting = true; |
| 71 | if (IsHandleCreated) |
| 72 | { |
| 73 | var context = ImmGetContext(Handle); |
| 74 | if (context != IntPtr.Zero) { ImmNotifyIME(context, 0x15, 4, 0); ImmReleaseContext(Handle, context); } |
| 75 | } |
| 76 | Clear(); highSurrogate = null; resetting = false; |
| 77 | } |
| 78 | |
| 79 | protected override bool IsInputKey(Keys keyData) => true; |
| 80 | protected override bool ProcessCmdKey(ref Message msg, Keys keyData) |
| 81 | { |
| 82 | if (!composing && (keyData & (Keys.Control | Keys.Alt)) != 0) |
| 83 | { |
| 84 | ReadKeyMessage(msg); |
| 85 | Key(keyData & Keys.KeyCode, true); |
| 86 | return true; |
| 87 | } |
| 88 | return base.ProcessCmdKey(ref msg, keyData); |
| 89 | } |
| 90 | protected override void OnKeyDown(KeyEventArgs e) |
| 91 | { |
| 92 | lastKey = e.KeyCode; |
| 93 | if (!composing && (e.Control || e.Alt || IsCommand(e.KeyCode))) |
| 94 | { Key(e.KeyCode, true); e.Handled = true; } |
| 95 | } |
| 96 | protected override void OnKeyUp(KeyEventArgs e) |
| 97 | { Key(e.KeyCode, false); e.Handled = true; } |
| 98 | protected override void OnKeyPress(KeyPressEventArgs e) |
| 99 | { |
| 100 | if (composing || resetting) return; |
| 101 | e.Handled = true; |
| 102 | if (char.IsHighSurrogate(e.KeyChar)) { highSurrogate = e.KeyChar; return; } |
| 103 | if (char.IsLowSurrogate(e.KeyChar) && highSurrogate is char first) |
| 104 | { Emit("input", new string([first, e.KeyChar])); highSurrogate = null; return; } |
| 105 | highSurrogate = null; |
| 106 | if (!char.IsControl(e.KeyChar)) |
| 107 | { |
| 108 | if (e.KeyChar <= 127) Key(lastKey, true, e.KeyChar.ToString()); |
| 109 | else Emit("input", e.KeyChar.ToString()); |
| 110 | } |
| 111 | } |
| 112 | protected override void OnTextChanged(EventArgs e) |
| 113 | { |
| 114 | base.OnTextChanged(e); |
| 115 | if (!composing && !resetting && Text.Length > 0) Clear(); |
| 116 | } |
| 117 | private static bool IsCommand(Keys key) => key is Keys.Enter or Keys.Tab or Keys.Back or Keys.Delete or Keys.Escape or |
| 118 | Keys.Left or Keys.Right or Keys.Up or Keys.Down or Keys.Home or Keys.End or Keys.PageUp or Keys.PageDown or |
| 119 | Keys.ShiftKey or Keys.ControlKey or Keys.Menu or Keys.LWin or Keys.RWin or Keys.CapsLock or Keys.Insert or |
| 120 | Keys.PrintScreen or Keys.Scroll or Keys.Pause or Keys.NumLock or Keys.Apps or Keys.Clear || key >= Keys.F1 && key <= Keys.F24; |
| 121 | |
| 122 | private void Key(Keys key, bool down, string? text = null) |
| 123 | { |
| 124 | if (owner.Length == 0) return; |
| 125 | var pair = key switch { |
| 126 | Keys.Enter => ("Enter", "Enter"), Keys.Tab => ("Tab", "Tab"), Keys.Back => ("Backspace", "Backspace"), |
| 127 | Keys.Delete => ("Delete", "Delete"), Keys.Escape => ("Escape", "Escape"), Keys.Left => ("ArrowLeft", "ArrowLeft"), |
| 128 | Keys.Right => ("ArrowRight", "ArrowRight"), Keys.Up => ("ArrowUp", "ArrowUp"), Keys.Down => ("ArrowDown", "ArrowDown"), |
| 129 | Keys.ShiftKey => ("Shift", "ShiftLeft"), Keys.ControlKey => ("Control", "ControlLeft"), Keys.Menu => ("Alt", "AltLeft"), |
| 130 | Keys.LWin => ("Meta", "MetaLeft"), Keys.RWin => ("Meta", "MetaRight"), Keys.CapsLock => ("CapsLock", "CapsLock"), |
| 131 | Keys.Home => ("Home", "Home"), Keys.End => ("End", "End"), Keys.PageUp => ("PageUp", "PageUp"), Keys.PageDown => ("PageDown", "PageDown"), |
| 132 | Keys.Space => (" ", "Space"), Keys.Insert => ("Insert", "Insert"), Keys.PrintScreen => ("PrintScreen", "PrintScreen"), |
| 133 | Keys.Scroll => ("ScrollLock", "ScrollLock"), Keys.Pause => ("Pause", "Pause"), Keys.NumLock => ("NumLock", "NumLock"), |
| 134 | Keys.Apps => ("ContextMenu", "ContextMenu"), Keys.Clear => ("Clear", "Numpad5"), |
| 135 | Keys.OemSemicolon => (";", "Semicolon"), Keys.Oemplus => ("=", "Equal"), Keys.Oemcomma => (",", "Comma"), |
| 136 | Keys.OemMinus => ("-", "Minus"), Keys.OemPeriod => (".", "Period"), Keys.OemQuestion => ("/", "Slash"), |
| 137 | Keys.Oemtilde => ("`", "Backquote"), Keys.OemOpenBrackets => ("[", "BracketLeft"), Keys.OemPipe => ("\\", "Backslash"), |
| 138 | Keys.OemCloseBrackets => ("]", "BracketRight"), Keys.OemQuotes => ("'", "Quote"), Keys.OemBackslash => ("\\", "IntlBackslash"), |
| 139 | Keys.Multiply => ("*", "NumpadMultiply"), Keys.Add => ("+", "NumpadAdd"), Keys.Subtract => ("-", "NumpadSubtract"), |
| 140 | Keys.Decimal => (".", "NumpadDecimal"), Keys.Divide => ("/", "NumpadDivide"), Keys.Separator => (",", "NumpadComma"), |
| 141 | _ when key >= Keys.A && key <= Keys.Z => (key.ToString().ToLowerInvariant(), "Key" + key), |
| 142 | _ when key >= Keys.D0 && key <= Keys.D9 => (((int)key - (int)Keys.D0).ToString(), "Digit" + ((int)key - (int)Keys.D0)), |
| 143 | _ when key >= Keys.NumPad0 && key <= Keys.NumPad9 => (((int)key - (int)Keys.NumPad0).ToString(), "Numpad" + ((int)key - (int)Keys.NumPad0)), |
| 144 | _ when key >= Keys.F1 && key <= Keys.F24 => (key.ToString(), key.ToString()), |
| 145 | _ => (text ?? "Unidentified", "Unidentified") |
| 146 | }; |
| 147 | var code = key switch { |
| 148 | Keys.Enter when extendedKey => "NumpadEnter", |
| 149 | Keys.ShiftKey when scanCode == 0x36 => "ShiftRight", |
| 150 | Keys.ControlKey when extendedKey => "ControlRight", |
| 151 | Keys.Menu when extendedKey => "AltRight", |
| 152 | _ => pair.Item2, |
| 153 | }; |
| 154 | if (!extendedKey && key is Keys.Insert or Keys.Delete or Keys.Home or Keys.End or Keys.PageUp or Keys.PageDown or |
| 155 | Keys.Left or Keys.Right or Keys.Up or Keys.Down or Keys.Clear) |
| 156 | { |
| 157 | code = scanCode switch { |
| 158 | 0x47 => "Numpad7", 0x48 => "Numpad8", 0x49 => "Numpad9", 0x4b => "Numpad4", 0x4c => "Numpad5", |
| 159 | 0x4d => "Numpad6", 0x4f => "Numpad1", 0x50 => "Numpad2", 0x51 => "Numpad3", 0x52 => "Numpad0", |
| 160 | 0x53 => "NumpadDecimal", _ => code, |
| 161 | }; |
| 162 | } |
| 163 | publish(new() { ["owner"] = owner, ["kind"] = down ? "keydown" : "keyup", ["key"] = text ?? pair.Item1, |
| 164 | ["code"] = code, ["textKey"] = text != null, ["repeat"] = repeating, |
| 165 | ["ctrlKey"] = (ModifierKeys & Keys.Control) != 0, ["altKey"] = (ModifierKeys & Keys.Alt) != 0, |
| 166 | ["shiftKey"] = (ModifierKeys & Keys.Shift) != 0, ["metaKey"] = false, |
| 167 | ["modifierCapsLock"] = IsKeyLocked(Keys.CapsLock) }); |
| 168 | } |
| 169 | |
| 170 | private void ReadKeyMessage(Message message) |
| 171 | { |
| 172 | scanCode = (int)((message.LParam.ToInt64() >> 16) & 0xff); |
| 173 | extendedKey = (message.LParam.ToInt64() & (1L << 24)) != 0; |
| 174 | repeating = (message.LParam.ToInt64() & (1L << 30)) != 0; |
| 175 | } |
| 176 | |
| 177 | protected override void WndProc(ref Message message) |
| 178 | { |
| 179 | const int Start = 0x10d, End = 0x10e, Composition = 0x10f; |
| 180 | bool committed = false; |
| 181 | if (message.Msg is 0x100 or 0x101 or 0x104 or 0x105) ReadKeyMessage(message); |
| 182 | if (!resetting && owner.Length > 0) |
| 183 | { |
| 184 | if (message.Msg == Start) { composing = true; Emit("compositionstart"); } |
| 185 | if (message.Msg == Composition) |
| 186 | { |
| 187 | var context = ImmGetContext(Handle); |
| 188 | if (context != IntPtr.Zero) |
| 189 | { |
| 190 | var flags = (int)message.LParam; |
| 191 | if ((flags & 0x800) != 0) |
| 192 | { |
| 193 | Emit("compositionend", CompositionText(context, 0x800)); composing = false; |
| 194 | committed = true; |
| 195 | BeginInvoke(() => { if (!composing && !IsDisposed) Clear(); }); |
| 196 | } |
| 197 | if ((flags & 8) != 0) |
| 198 | { |
| 199 | if (!composing) { composing = true; Emit("compositionstart"); } |
| 200 | var text = CompositionText(context, 8); |
| 201 | var cursor = Math.Clamp(ImmGetCompositionString(context, 0x80, null, 0), 0, text.Length); |
| 202 | Emit("compositionupdate", text, cursor, cursor); |
| 203 | } |
| 204 | ImmReleaseContext(Handle, context); |
| 205 | } |
| 206 | PositionCandidates(); |
| 207 | } |
| 208 | if (message.Msg == End && composing) { composing = false; Emit("compositionend", ""); } |
| 209 | } |
| 210 | |
| 211 | |
| 212 | if (committed) { message.Result = IntPtr.Zero; return; } |
| 213 | |
| 214 | if (message.Msg == 0xf) { ValidateRect(Handle, IntPtr.Zero); message.Result = IntPtr.Zero; return; } |
| 215 | base.WndProc(ref message); |
| 216 | if (IsHandleCreated) HideCaret(Handle); |
| 217 | } |
| 218 | |
| 219 | private static string CompositionText(IntPtr context, int index) |
| 220 | { |
| 221 | var length = ImmGetCompositionString(context, index, null, 0); |
| 222 | if (length <= 0 || length > 16384) return ""; |
| 223 | var bytes = new byte[length]; |
| 224 | var count = ImmGetCompositionString(context, index, bytes, bytes.Length); |
| 225 | return count > 0 ? Encoding.Unicode.GetString(bytes, 0, count) : ""; |
| 226 | } |
| 227 | private void PositionCandidates() |
| 228 | { |
| 229 | if (!IsHandleCreated) return; |
| 230 | var context = ImmGetContext(Handle); |
| 231 | if (context == IntPtr.Zero) return; |
| 232 | var candidate = new Candidate { Style = 0x80, Point = new Point(0, Height), Area = new Rect { Bottom = Height, Right = 1 } }; |
| 233 | ImmSetCandidateWindow(context, ref candidate); |
| 234 | ImmReleaseContext(Handle, context); |
| 235 | } |
| 236 | [StructLayout(LayoutKind.Sequential)] private struct Rect { public int Left, Top, Right, Bottom; } |
| 237 | [StructLayout(LayoutKind.Sequential)] private struct Candidate { public int Index, Style; public Point Point; public Rect Area; } |
| 238 | [DllImport("imm32.dll")] private static extern IntPtr ImmGetContext(IntPtr window); |
| 239 | [DllImport("imm32.dll")] private static extern bool ImmReleaseContext(IntPtr window, IntPtr context); |
| 240 | [DllImport("imm32.dll", EntryPoint = "ImmGetCompositionStringW")] private static extern int ImmGetCompositionString(IntPtr context, int index, byte[]? data, int length); |
| 241 | [DllImport("imm32.dll")] private static extern bool ImmSetCandidateWindow(IntPtr context, ref Candidate candidate); |
| 242 | [DllImport("imm32.dll")] private static extern bool ImmNotifyIME(IntPtr context, int action, int index, int value); |
| 243 | [DllImport("user32.dll")] private static extern bool HideCaret(IntPtr window); |
| 244 | [DllImport("user32.dll")] private static extern bool ValidateRect(IntPtr window, IntPtr rect); |
| 245 | } |