Repository navigation
Expand file tree
/
Copy pathEngine.cpp
More file actions
319 lines (318 loc) · 13.3 KB
/
Copy pathEngine.cpp
File metadata and controls
319 lines (318 loc) · 13.3 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
#include "Engine.h"
#include "Interceptor.h"
#include <algorithm>
#include <chrono>
#include <exception>
#include <system_error>
namespace MouseControl {
namespace {
void Require(const Interceptor::Send_Result &sent, std::size_t expected) {
if (!sent || sent.accepted != expected)
throw std::system_error(sent.error ? sent.error : ERROR_WRITE_FAULT, std::system_category(),
"Forward mouse/keyboard input");
}
std::wstring Wide(const char *text) {
const int n = MultiByteToWideChar(CP_UTF8, 0, text, -1, nullptr, 0);
if (!n)
return L"Unknown driver failure";
std::wstring out(static_cast<std::size_t>(n), L'\0');
MultiByteToWideChar(CP_UTF8, 0, text, -1, out.data(), n);
out.pop_back();
return out;
}
class NativeTransport final : public Transport {
public:
std::vector<Source> Open() override {
using namespace Interceptor;
if (Get_Status().version != IC_VERSION)
throw std::system_error(ERROR_REVISION_MISMATCH, std::system_category(),
"Incompatible Keyboard & Mouse driver");
const auto init = Init_AllDevices();
if (!init.ready)
throw std::system_error(init.error ? init.error
: init.reboot_required ? ERROR_SUCCESS_REBOOT_REQUIRED
: ERROR_NOT_READY,
std::system_category(), "Initialize Keyboard & Mouse devices");
std::vector<Source> mice;
for (const auto &d : Get_Devices())
if (d.type == static_cast<unsigned>(Device_Type::Mouse)) {
const auto length = static_cast<std::size_t>(
std::find(std::begin(d.name), std::end(d.name), 0) - std::begin(d.name));
std::wstring name(reinterpret_cast<const wchar_t *>(d.name), length);
if (name.empty())
name = L"Mouse " + std::to_wstring(d.id);
mice.push_back({d.id, std::move(name)});
}
if (mice.empty())
throw std::system_error(ERROR_DEVICE_NOT_CONNECTED, std::system_category(),
"No associated physical mouse is available");
return mice;
}
std::uint64_t Read(DWORD timeout, HANDLE wake,
const std::function<void(const Physical &)> &receive) override {
using namespace Interceptor;
auto batch = Get_Input_With_Timeout(timeout, wake);
std::exception_ptr failure;
for (const auto &input : batch) {
Physical p;
p.device = input.device;
if (const auto *mouse = input.Get<Mouse_Input>()) {
p.mouse = true;
for (unsigned i = 0; i < 5; ++i) {
if (mouse->stroke.button_flags & (1u << (i * 2)))
p.buttonsDown |= static_cast<std::uint8_t>(1u << i);
if (mouse->stroke.button_flags & (2u << (i * 2)))
p.buttonsUp |= static_cast<std::uint8_t>(1u << i);
}
} else if (const auto *keyboard = input.Get<Keyboard_Input>()) {
p.key = {keyboard->stroke.make_code,
static_cast<std::uint16_t>(keyboard->stroke.flags & (KeyE0 | KeyE1))};
p.down = (keyboard->stroke.flags & KeyUp) == 0;
} else
continue;
try {
if (!failure)
receive(p);
} catch (...) {
failure = std::current_exception();
}
}
// Always forward the physical batch, even if a user-mode state update failed.
const auto size = batch.size();
std::size_t forwarded = 0;
const auto deadline = GetTickCount64() + 250;
while (forwarded < size) {
const auto sent = Send_Input(batch);
forwarded += sent.accepted;
if (sent.error == ERROR_BUSY && forwarded < size && GetTickCount64() < deadline) {
SwitchToThread();
continue;
}
Require(sent, size - (forwarded - sent.accepted));
}
if (failure)
std::rethrow_exception(failure);
return size;
}
bool Send(const Movement &movement) override {
Interceptor::Mouse_Input packet{};
packet.device = movement.device;
packet.stroke.x = movement.x;
packet.stroke.y = movement.y;
const auto sent = Interceptor::Send_Input(packet);
if (!sent.accepted && sent.error == ERROR_BUSY)
return false;
Require(sent, 1);
return true;
}
void Close() noexcept override {
try {
Interceptor::Destroy_Context();
} catch (...) {
}
}
};
std::wstring DriverHint(DWORD code) {
if (code == ERROR_FILE_NOT_FOUND || code == ERROR_PATH_NOT_FOUND ||
code == ERROR_SERVICE_DOES_NOT_EXIST)
return L"Install Interceptor Keyboard & Mouse using Driver setup, restart if requested, "
L"then switch ON.";
if (code == ERROR_EVALUATION_EXPIRATION)
return L"The shared one-hour driver demo has expired. Use Windows Restart for a new "
L"allowance, then reopen MouseControl.";
if (code == ERROR_SUCCESS_REBOOT_REQUIRED || code == ERROR_SUCCESS_RESTART_REQUIRED)
return L"Windows needs a restart to finish driver associations. Restart, then reopen "
L"MouseControl.";
if (code == ERROR_ACCESS_DENIED)
return L"Administrator rights are required. Reopen MouseControl and accept the Windows "
L"administrator prompt.";
return L"Close other capture applications. Check Driver setup > Diagnose, reconnect the device "
L"if necessary, then switch ON.";
}
} // namespace
std::shared_ptr<Transport> DriverTransport() {
return std::make_shared<NativeTransport>();
}
std::int64_t Clock() noexcept {
return std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
Engine::Engine(std::shared_ptr<Transport> t) : transport_(std::move(t)) {
wake_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if (!wake_)
throw std::system_error(GetLastError(), std::system_category(),
"Create capture wake event");
}
Engine::~Engine() {
Stop();
CloseHandle(wake_);
}
void Engine::Start(HWND owner, const Settings &settings) {
if (worker_.joinable())
throw std::logic_error("MouseControl is already running.");
Configure(settings);
owner_ = owner;
worker_ = std::thread([this] { Run(); });
}
void Engine::Stop() noexcept {
stopping_ = true;
desired_ = false;
SetEvent(wake_);
if (worker_.joinable())
worker_.join();
}
void Engine::Configure(const Settings &s) {
Validate(s);
std::atomic_store(&settings_, std::make_shared<const Settings>(s));
SetEvent(wake_);
}
void Engine::Running(bool enabled) {
desired_ = enabled;
SetEvent(wake_);
}
void Engine::Suspended(bool suspended) {
suspended_ = suspended;
SetEvent(wake_);
}
void Engine::RecordKey(bool enabled) {
recording_ = enabled;
SetEvent(wake_);
}
void Engine::Publish(const Snapshot &value) {
{
std::lock_guard<std::mutex> lock(mutex_);
snapshot_ = value;
}
if (owner_ && !notified_.exchange(true) && !PostMessageW(owner_, SnapshotMessage, 0, 0))
notified_ = false;
}
Snapshot Engine::Read() {
notified_ = false;
std::lock_guard<std::mutex> lock(mutex_);
return snapshot_;
}
void Engine::Run() {
Snapshot state;
std::int64_t published = 0;
while (!stopping_) {
if (!desired_) {
state.paused = true;
state.active = state.connected = false;
state.recording = recording_;
if (!state.error) {
state.title = L"Remap OFF";
state.detail = L"Capture released. Physical input passes through normally.";
}
Publish(state);
WaitForSingleObject(wake_, INFINITE);
continue;
}
try {
auto configured = std::atomic_load(&settings_);
Scheduler scheduler(*configured);
const auto sources = transport_->Open();
std::optional<Movement> pending;
for (const auto &source : sources)
scheduler.Mouse(source.id, 0, 0);
state.error = 0;
state.paused = false;
state.connected = true;
state.target = sources.size() == 1
? sources.front().name
: L"Auto · " + std::to_wstring(sources.size()) + L" physical mice";
state.title = L"Ready";
state.detail.clear();
Publish(state);
while (desired_ && !stopping_) {
const auto next = std::atomic_load(&settings_);
if (next != configured) {
pending.reset();
scheduler.Configure(*next);
configured = next;
}
scheduler.Enable(!suspended_ && !recording_);
const auto due = scheduler.Deadline();
const auto now = Clock();
const auto timeout =
pending ? 0
: due ? static_cast<DWORD>(*due <= now ? 0
: std::min<std::int64_t>(
600000, (*due - now + 999) / 1000))
: INFINITE;
const bool before = state.active;
const auto beforeRecord = state.recordVersion;
state.physical += transport_->Read(timeout, wake_, [&](const Physical &input) {
if (input.mouse)
scheduler.Mouse(input.device, input.buttonsDown, input.buttonsUp);
else {
scheduler.Keyboard(input.device, input.key, input.down);
if (recording_ && input.down) {
state.recorded = input.key.code == 1 && !input.key.extended
? std::optional<Key>{}
: input.key;
++state.recordVersion;
recording_ = false;
}
}
});
// Re-read cancellation/focus flags after the wait and before every synthetic
// packet. No look-ahead queue of future movements is ever submitted to the driver.
const auto newest = std::atomic_load(&settings_);
if (newest != configured) {
pending.reset();
scheduler.Configure(*newest);
configured = newest;
}
scheduler.Enable(desired_ && !stopping_ && !suspended_ && !recording_);
scheduler.Reconcile(Clock());
if (!scheduler.Active())
pending.reset();
if (!pending)
pending = scheduler.Tick(Clock());
if (pending && transport_->Send(*pending)) {
pending.reset();
++state.movements;
}
state.active = scheduler.Active();
state.suspended = suspended_;
state.recording = recording_;
if (scheduler.Target()) {
const auto source =
std::find_if(sources.begin(), sources.end(),
[&](const auto &s) { return s.id == scheduler.Target(); });
state.target = source == sources.end()
? L"Mouse " + std::to_wstring(scheduler.Target())
: source->name;
}
state.title = state.active ? L"Sequence running"
: state.suspended ? L"Ready · use outside this window"
: L"Ready · hold your trigger";
const auto stamp = Clock();
if (before != state.active || beforeRecord != state.recordVersion ||
stamp - published >= 50000) {
Publish(state);
published = stamp;
}
}
} catch (const std::system_error &error) {
state.error = static_cast<DWORD>(error.code().value());
state.title = L"Driver needs attention";
state.detail = DriverHint(state.error) + L"\n\n" + Wide(error.what()) +
L" (Windows error " + std::to_wstring(state.error) + L").";
desired_ = false;
} catch (const std::exception &error) {
state.error = ERROR_GEN_FAILURE;
state.title = L"Capture stopped safely";
state.detail = Wide(error.what());
desired_ = false;
}
transport_->Close();
state.connected = state.active = false;
}
transport_->Close();
state.active = state.connected = false;
state.title = L"Stopped";
Publish(state);
}
} // namespace MouseControl