Repository navigation
Expand file tree
/
Copy pathAutoFiller.cpp
More file actions
533 lines (439 loc) · 13.4 KB
/
Copy pathAutoFiller.cpp
File metadata and controls
533 lines (439 loc) · 13.4 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include "Buffer.h"
#include "BufferCommand.h"
#include "ConsoleLog.h"
#include "InputRouter.h"
#include "LlmProvider.h"
#include "Prompt.h"
#include "SuggestionsScheduler.h"
#include "SuggestionWindow.h"
#include <SuggestionProcessingProvider.h>
#include <deque>
#include <memory>
#include <optional>
#include <string_view>
#include <utility>
#include <vector>
#pragma comment(lib, "User32.lib")
namespace
{
constexpr std::wstring_view DISABLE_LLM_ARGUMENT = L"DISABLE_LLM";
HHOOK g_keyboardHook = nullptr;
HHOOK g_mouseHook = nullptr;
bool g_SuppressNextTabUp = false;
bool g_SuppressNextEscapeUp = false;
HWINEVENTHOOK g_foregroundHook = nullptr;
HWINEVENTHOOK g_focusHook = nullptr;
DWORD g_mainThreadId = 0;
std::shared_ptr<ConsoleLog> g_Log = nullptr;
std::shared_ptr<Buffer> g_Buffer = nullptr;
std::shared_ptr<Prompt> g_Prompt = nullptr;
std::shared_ptr<InputRouter> g_InputRouter = nullptr;
std::shared_ptr<LlmProvider> g_LlmProvider = nullptr;
std::shared_ptr<SuggestionProcessingProvider> g_SuggestionProcessingProvider = nullptr;
std::shared_ptr<SuggestionsScheduler> g_SuggestionsScheduler = nullptr;
std::unique_ptr<SuggestionWindow> g_SuggestionWindow = nullptr;
bool HasArgument(int argc, wchar_t* argv[], std::wstring_view argument)
{
for (int i = 1; i < argc; ++i)
{
if (argv[i] && std::wstring_view(argv[i]) == argument)
return true;
}
return false;
}
void HideSuggestionWindow()
{
g_SuggestionWindow.reset();
}
void ShowSuggestionWindow(std::wstring_view suggestion)
{
if (suggestion.empty())
{
HideSuggestionWindow();
return;
}
POINT cursorPosition{};
if (GetCursorPos(&cursorPosition))
{
g_SuggestionWindow = std::make_unique<SuggestionWindow>(
cursorPosition.x + 20,
cursorPosition.y + 20
);
}
else
{
g_SuggestionWindow = std::make_unique<SuggestionWindow>();
}
g_SuggestionWindow->Show(suggestion);
}
void PrintReadySuggestions()
{
if (!g_SuggestionsScheduler || !g_Log || !g_SuggestionProcessingProvider)
return;
while (true)
{
std::optional<ReadySuggestionResponse> readyResponse =
g_SuggestionsScheduler->TakeLatestResponse();
if (!readyResponse)
return;
if (!readyResponse->Response.Success)
{
if (g_SuggestionsScheduler->TrySetLastSuggestion(
readyResponse->InputVersion,
std::deque<std::wstring>{}))
{
g_Log->PrintSuggestionError(readyResponse->Response.Error);
HideSuggestionWindow();
}
continue;
}
SuggestionProcessingResult processingResult =
g_SuggestionProcessingProvider->Process(
readyResponse->UserInput,
readyResponse->Response.Text
);
if (!processingResult.Success)
{
if (g_SuggestionsScheduler->TrySetLastSuggestion(
readyResponse->InputVersion,
std::deque<std::wstring>{}))
{
g_Log->PrintSuggestionError(processingResult.Error);
HideSuggestionWindow();
}
continue;
}
std::wstring suggestion = processingResult.Text();
std::deque<std::wstring> suggestionTokens = std::move(processingResult.Tokens);
if (!g_SuggestionsScheduler->TrySetLastSuggestion(
readyResponse->InputVersion,
std::move(suggestionTokens)))
{
continue;
}
g_Log->PrintSuggestion(suggestion);
ShowSuggestionWindow(suggestion);
}
}
bool IsTabKeyDown(WPARAM message, const KBDLLHOOKSTRUCT& keyboard)
{
if ((keyboard.flags & LLKHF_INJECTED) != 0)
{
return false;
}
return
keyboard.vkCode == VK_TAB &&
(message == WM_KEYDOWN || message == WM_SYSKEYDOWN);
}
bool IsTabKeyUp(WPARAM message, const KBDLLHOOKSTRUCT& keyboard)
{
return
keyboard.vkCode == VK_TAB &&
(message == WM_KEYUP || message == WM_SYSKEYUP);
}
bool IsEscapeKeyDown(WPARAM message, const KBDLLHOOKSTRUCT& keyboard)
{
if ((keyboard.flags & LLKHF_INJECTED) != 0)
{
return false;
}
return
keyboard.vkCode == VK_ESCAPE &&
(message == WM_KEYDOWN || message == WM_SYSKEYDOWN);
}
bool IsEscapeKeyUp(WPARAM message, const KBDLLHOOKSTRUCT& keyboard)
{
return
keyboard.vkCode == VK_ESCAPE &&
(message == WM_KEYUP || message == WM_SYSKEYUP);
}
bool InsertText(std::wstring_view text)
{
if (text.empty())
{
return false;
}
std::vector<INPUT> inputs;
inputs.reserve(text.size() * 2);
for (wchar_t ch : text)
{
INPUT keyDown{};
keyDown.type = INPUT_KEYBOARD;
keyDown.ki.wScan = ch;
keyDown.ki.dwFlags = KEYEVENTF_UNICODE;
INPUT keyUp = keyDown;
keyUp.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
inputs.push_back(keyDown);
inputs.push_back(keyUp);
}
const UINT sent = SendInput(
static_cast<UINT>(inputs.size()),
inputs.data(),
sizeof(INPUT)
);
return sent == static_cast<UINT>(inputs.size());
}
bool TryAcceptLastSuggestion()
{
if (!g_SuggestionsScheduler)
{
return false;
}
std::optional<std::wstring> suggestion = g_SuggestionsScheduler->TakeNextSuggestion();
if (!suggestion || suggestion->empty())
return false;
if (!InsertText(*suggestion))
return false;
g_Buffer->AppendText(*suggestion);
BufferState state = g_Buffer->Snapshot();
if (g_InputRouter)
{
g_InputRouter->SetExpectedTextFromInjectedInput(state.Text);
}
if (g_Log)
g_Log->PrintState(L"suggestion-accepted", state);
std::optional<std::wstring> remainingSuggestion =
g_SuggestionsScheduler->PeekLastSuggestion();
if (remainingSuggestion && !remainingSuggestion->empty())
{
ShowSuggestionWindow(*remainingSuggestion);
}
else
{
HideSuggestionWindow();
g_SuggestionsScheduler->NotifyInputProcessed(state);
}
return true;
}
bool TryDismissLastSuggestion()
{
if (!g_SuggestionWindow || !g_SuggestionWindow->IsVisible())
{
return false;
}
HideSuggestionWindow();
if (g_SuggestionsScheduler)
{
g_SuggestionsScheduler->ResetLastSuggestion();
}
return true;
}
void RunCommand(CommandPtr command)
{
if (!command || !command->ShouldLog())
{
return;
}
HideSuggestionWindow();
command->Execute(*g_Buffer);
BufferState state = g_Buffer->Snapshot();
if (g_Log)
{
g_Log->PrintState(command->Reason(), state);
}
if (g_SuggestionsScheduler)
{
g_SuggestionsScheduler->ResetLastSuggestion();
g_SuggestionsScheduler->NotifyInputProcessed(state);
}
}
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode == HC_ACTION)
{
const auto* keyboard = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam);
if (IsTabKeyDown(wParam, *keyboard) && TryAcceptLastSuggestion())
{
g_SuppressNextTabUp = true;
return 1;
}
if (IsEscapeKeyDown(wParam, *keyboard) && TryDismissLastSuggestion())
{
g_SuppressNextEscapeUp = true;
return 1;
}
if (g_SuppressNextTabUp && IsTabKeyUp(wParam, *keyboard))
{
g_SuppressNextTabUp = false;
return 1;
}
if (g_SuppressNextEscapeUp && IsEscapeKeyUp(wParam, *keyboard))
{
g_SuppressNextEscapeUp = false;
return 1;
}
RunCommand(g_InputRouter->ProcessKeyboardEvent(wParam, *keyboard));
}
return CallNextHookEx(g_keyboardHook, nCode, wParam, lParam);
}
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode == HC_ACTION)
{
RunCommand(g_InputRouter->ProcessMouseEvent(wParam));
}
return CallNextHookEx(g_mouseHook, nCode, wParam, lParam);
}
void CALLBACK WinEventProc(
HWINEVENTHOOK,
DWORD event,
HWND hwnd,
LONG idObject,
LONG idChild,
DWORD,
DWORD)
{
RunCommand(g_InputRouter->ProcessWindowEvent(event, hwnd, idObject, idChild));
}
BOOL WINAPI ConsoleCtrlHandler(DWORD ctrlType)
{
switch (ctrlType)
{
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
PostThreadMessageW(g_mainThreadId, WM_QUIT, 0, 0);
return TRUE;
default:
return FALSE;
}
}
bool InstallHooks()
{
HINSTANCE instance = GetModuleHandleW(nullptr);
g_keyboardHook = SetWindowsHookExW(
WH_KEYBOARD_LL,
KeyboardProc,
instance,
0
);
if (!g_keyboardHook)
{
g_Log->PrintHookInstallError(L"keyboard", GetLastError());
return false;
}
g_mouseHook = SetWindowsHookExW(
WH_MOUSE_LL,
MouseProc,
instance,
0
);
if (!g_mouseHook)
{
g_Log->PrintHookInstallError(L"mouse", GetLastError());
return false;
}
g_foregroundHook = SetWinEventHook(
EVENT_SYSTEM_FOREGROUND,
EVENT_SYSTEM_FOREGROUND,
nullptr,
WinEventProc,
0,
0,
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS
);
if (!g_foregroundHook)
{
g_Log->PrintHookInstallError(L"foreground event", GetLastError());
return false;
}
g_focusHook = SetWinEventHook(
EVENT_OBJECT_FOCUS,
EVENT_OBJECT_FOCUS,
nullptr,
WinEventProc,
0,
0,
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS
);
if (!g_focusHook)
{
g_Log->PrintHookInstallError(L"focus event", GetLastError());
return false;
}
return true;
}
void UninstallHooks()
{
if (g_keyboardHook)
{
UnhookWindowsHookEx(g_keyboardHook);
g_keyboardHook = nullptr;
}
if (g_mouseHook)
{
UnhookWindowsHookEx(g_mouseHook);
g_mouseHook = nullptr;
}
if (g_foregroundHook)
{
UnhookWinEvent(g_foregroundHook);
g_foregroundHook = nullptr;
}
if (g_focusHook)
{
UnhookWinEvent(g_focusHook);
g_focusHook = nullptr;
}
}
}
int wmain(int argc, wchar_t* argv[])
{
g_mainThreadId = GetCurrentThreadId();
const bool disableLlm = HasArgument(argc, argv, DISABLE_LLM_ARGUMENT);
MSG msg;
PeekMessageW(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE);
g_Log = std::make_shared<ConsoleLog>();
g_Buffer = std::make_shared<Buffer>();
g_InputRouter = std::make_shared<InputRouter>(g_mainThreadId, INPUT_ROUTER_MESSAGE);
g_Prompt = std::make_shared<Prompt>();
g_LlmProvider = std::make_shared<LlmProvider>(*g_Log, disableLlm);
g_SuggestionProcessingProvider = std::make_shared<SuggestionProcessingProvider>();
g_SuggestionsScheduler = std::make_shared<SuggestionsScheduler>(
g_Buffer,
g_Prompt,
g_LlmProvider,
g_mainThreadId,
SUGGESTION_READY_MESSAGE
);
SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
if (!InstallHooks())
{
UninstallHooks();
return 1;
}
while (GetMessageW(&msg, nullptr, 0, 0) > 0)
{
if (msg.message == SUGGESTION_READY_MESSAGE)
{
PrintReadySuggestions();
continue;
}
if (msg.message == INPUT_ROUTER_MESSAGE)
{
RunCommand(g_InputRouter->ProcessPendingInputEvent());
continue;
}
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
UninstallHooks();
g_SuggestionsScheduler.reset();
g_SuggestionProcessingProvider.reset();
HideSuggestionWindow();
g_InputRouter.reset();
g_Log->PrintStopped();
return 0;
}