-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTextExpansionService.cs
More file actions
214 lines (181 loc) · 7.02 KB
/
TextExpansionService.cs
File metadata and controls
214 lines (181 loc) · 7.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
using System.Runtime.InteropServices;
using System.Text;
namespace NoteUI;
public class TextExpansionService
{
private readonly SnippetManager _snippetManager;
private readonly StringBuilder _buffer = new(64);
private IntPtr _hookId;
private LowLevelKeyboardProc? _hookProc;
private bool _isSendingInput;
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private const uint KEYEVENTF_UNICODE = 0x0004;
private const uint KEYEVENTF_KEYUP = 0x0002;
private const uint INPUT_KEYBOARD = 1;
private const uint LLKHF_INJECTED = 0x00000010;
public TextExpansionService(SnippetManager snippetManager)
{
_snippetManager = snippetManager;
}
public void Start()
{
if (_hookId != IntPtr.Zero) return;
_hookProc = HookCallback;
using var process = System.Diagnostics.Process.GetCurrentProcess();
using var module = process.MainModule!;
_hookId = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc,
GetModuleHandle(module.ModuleName), 0);
}
public void Stop()
{
if (_hookId != IntPtr.Zero)
{
UnhookWindowsHookEx(_hookId);
_hookId = IntPtr.Zero;
}
_hookProc = null;
}
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN && !_isSendingInput)
{
var kb = Marshal.PtrToStructure<KBDLLHOOKSTRUCT>(lParam);
// Skip injected keystrokes (our own SendInput)
if ((kb.flags & LLKHF_INJECTED) != 0)
return CallNextHookEx(_hookId, nCode, wParam, lParam);
var vk = kb.vkCode;
// Trigger keys: Space, Tab, Enter
if (vk == 0x20 || vk == 0x09 || vk == 0x0D)
{
var keyword = _buffer.ToString();
_buffer.Clear();
if (!string.IsNullOrEmpty(keyword))
{
var snippet = _snippetManager.FindByTrigger(keyword);
if (snippet != null)
{
ExpandSnippet(keyword, snippet.Content);
return (IntPtr)1;
}
}
return CallNextHookEx(_hookId, nCode, wParam, lParam);
}
// Backspace: remove last char from buffer
if (vk == 0x08)
{
if (_buffer.Length > 0)
_buffer.Remove(_buffer.Length - 1, 1);
return CallNextHookEx(_hookId, nCode, wParam, lParam);
}
// Escape, arrows, modifiers, etc. -> clear buffer
if (vk < 0x20 || vk >= 0xA0)
{
// Allow shift (0x10) through without clearing
if (vk != 0x10 && vk != 0x11 && vk != 0x12)
_buffer.Clear();
return CallNextHookEx(_hookId, nCode, wParam, lParam);
}
// Convert VK to character using current keyboard layout
var ch = VkToChar(vk);
if (ch != '\0')
{
if (_buffer.Length >= 64)
_buffer.Remove(0, 1);
_buffer.Append(ch);
}
}
return CallNextHookEx(_hookId, nCode, wParam, lParam);
}
private void ExpandSnippet(string keyword, string content)
{
_isSendingInput = true;
try
{
// Send Backspace x keyword length to erase the keyword
var backspaces = keyword.Length;
var bsInputs = new INPUT[backspaces * 2];
for (int i = 0; i < backspaces; i++)
{
bsInputs[i * 2].type = INPUT_KEYBOARD;
bsInputs[i * 2].ki.wVk = 0x08; // VK_BACK
bsInputs[i * 2 + 1].type = INPUT_KEYBOARD;
bsInputs[i * 2 + 1].ki.wVk = 0x08;
bsInputs[i * 2 + 1].ki.dwFlags = KEYEVENTF_KEYUP;
}
SendInput((uint)bsInputs.Length, bsInputs, Marshal.SizeOf<INPUT>());
// Send content as Unicode characters
var chars = content.ToCharArray();
var charInputs = new INPUT[chars.Length * 2];
for (int i = 0; i < chars.Length; i++)
{
charInputs[i * 2].type = INPUT_KEYBOARD;
charInputs[i * 2].ki.wScan = chars[i];
charInputs[i * 2].ki.dwFlags = KEYEVENTF_UNICODE;
charInputs[i * 2 + 1].type = INPUT_KEYBOARD;
charInputs[i * 2 + 1].ki.wScan = chars[i];
charInputs[i * 2 + 1].ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
}
SendInput((uint)charInputs.Length, charInputs, Marshal.SizeOf<INPUT>());
}
finally
{
_isSendingInput = false;
}
}
private static char VkToChar(uint vk)
{
var keyboardState = new byte[256];
GetKeyboardState(keyboardState);
var scanCode = MapVirtualKey(vk, 0);
var sb = new StringBuilder(4);
var result = ToUnicode(vk, scanCode, keyboardState, sb, sb.Capacity, 0);
return result == 1 ? sb[0] : '\0';
}
// -- P/Invoke --
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
private struct KBDLLHOOKSTRUCT
{
public uint vkCode;
public uint scanCode;
public uint flags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Explicit, Size = 40)]
private struct INPUT
{
[FieldOffset(0)] public uint type;
[FieldOffset(8)] public KEYBDINPUT ki;
}
[StructLayout(LayoutKind.Sequential)]
private struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn,
IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll")]
private static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
[DllImport("user32.dll")]
private static extern uint MapVirtualKey(uint uCode, uint uMapType);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpKeyState,
StringBuilder pwszBuff, int cchBuff, uint wFlags);
}