-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripter_manager.cpp
More file actions
686 lines (587 loc) · 23.2 KB
/
Copy pathscripter_manager.cpp
File metadata and controls
686 lines (587 loc) · 23.2 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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// scripter_manager.cpp
#include "misc.h"
#include "scripter_manager.h"
#include "cmd_processor.h"
#include "cmd_stream_reader.h"
#include "pipe_streambuf.h"
#include "stringtool.h"
#include "inifile.h"
#include "nyamy_paths.h"
#include "mayu.h"
#include <process.h>
#include <atomic>
#include <random>
#include <vector>
//=============================================================================
// pending Setting slot
//=============================================================================
// Single-slot handoff from the scripter data thread (producer) to the tasktray
// window procedure (consumer). WM_ScripterSettingReady carries no payload: the
// Setting travels through this slot, so a notification that is posted but never
// dispatched (WM_QUIT, destroyed window, shutdown race) cannot leak it, and a
// stale HWND can no longer deliver a raw pointer to a foreign window procedure.
namespace
{
std::atomic<std::shared_ptr<Setting> > &pendingSettingSlot()
{
static std::atomic<std::shared_ptr<Setting> > slot;
return slot;
}
} // namespace
void ScripterManager::setPendingSetting(std::shared_ptr<Setting> i_setting)
{
// The superseded Setting, if any, is released as the returned temporary
// goes out of scope.
pendingSettingSlot().exchange(std::move(i_setting));
}
std::shared_ptr<Setting> ScripterManager::takePendingSetting()
{
return pendingSettingSlot().exchange(nullptr);
}
void ScripterManager::clearPendingSetting()
{
takePendingSetting();
}
//=============================================================================
// ScripterManager
//=============================================================================
ScripterManager::ScripterManager(SyncObject *i_soLog, std::wostream *i_log,
HWND i_hwndNotify)
: m_soLog(i_soLog)
, m_log(i_log)
, m_hwndNotify(i_hwndNotify)
, m_hCtrlWrite(INVALID_HANDLE_VALUE)
, m_hDataRead(INVALID_HANDLE_VALUE)
, m_hMsgRead(INVALID_HANDLE_VALUE)
, m_hScripterProcess(NULL)
, m_hDataThread(NULL)
, m_hMsgThread(NULL)
, m_hReaderStop(CreateEvent(NULL, TRUE, FALSE, NULL))
, m_quitSent(false)
, m_logLevel(kLogLevelNormal)
{
}
ScripterManager::~ScripterManager()
{
// Mayu normally stops the reader threads itself and leaves nothing to do
// here; this is the fallback for any other owner.
sendQuit();
waitForPendingStart();
forceStop(kScripterQuitGraceMillisec);
closeHandles();
// Release a Setting that was handed over but never dispatched, rather than
// keeping it alive until process exit.
clearPendingSetting();
if (m_hReaderStop)
CloseHandle(m_hReaderStop);
}
void ScripterManager::sendQuit()
{
if (m_quitSent) return;
m_quitSent = true;
{
std::lock_guard<std::mutex> lock(m_ctrlMutex);
if (m_ctrlWriter) {
try {
m_ctrlWriter->writeQuit();
m_ctrlStream->flush();
} catch (...) {}
if (m_ctrlStreambuf && m_ctrlStreambuf->wasBlocked()) {
m_ctrlStreambuf->clearBlocked();
if (m_log) {
Acquire a(m_soLog, LogLevel::Warn);
*m_log << L"ScripterManager: ctrl pipe full; Quit not "
L"delivered (closing the pipe still signals it)"
<< std::endl;
}
}
}
m_ctrlWriter.reset();
m_ctrlStream.reset();
m_ctrlStreambuf.reset();
}
// Closing the write end is the signal that always gets through: the
// scripter sees EOF on its ctrl pipe. CtrlId::Quit above is the early
// notice, not the guarantee.
if (m_hCtrlWrite != INVALID_HANDLE_VALUE) {
CloseHandle(m_hCtrlWrite);
m_hCtrlWrite = INVALID_HANDLE_VALUE;
}
}
void ScripterManager::stopReaders()
{
if (m_hReaderStop)
SetEvent(m_hReaderStop);
}
void ScripterManager::forceStop(DWORD i_graceMillisec)
{
stopReaders();
HANDLE h[3];
DWORD n = collectHandles(h, 3);
if (n == 0)
return;
if (WaitForMultipleObjects(n, h, TRUE, i_graceMillisec) != WAIT_TIMEOUT)
return;
// The scripter neither exited on its own nor terminated itself, so it is a
// foreign implementation, one wedged before its ctrl thread started, or one
// held alive by an error dialog. Kill it rather than let it outlive nyamy.
if (m_hScripterProcess) {
if (m_log) {
Acquire a(m_soLog, LogLevel::Warn);
*m_log << L"ScripterManager: scripter did not exit; terminating."
<< std::endl;
}
TerminateProcess(m_hScripterProcess, 1);
}
n = collectHandles(h, 3);
if (n > 0)
WaitForMultipleObjects(n, h, TRUE, kScripterKillWaitMillisec);
}
void ScripterManager::waitForPendingStart()
{
if (m_startFuture.valid())
m_startFuture.wait();
}
DWORD ScripterManager::collectHandles(HANDLE *buf, DWORD maxCount)
{
DWORD n = 0;
if (m_hScripterProcess && n < maxCount) buf[n++] = m_hScripterProcess;
if (m_hDataThread && n < maxCount) buf[n++] = m_hDataThread;
if (m_hMsgThread && n < maxCount) buf[n++] = m_hMsgThread;
return n;
}
void ScripterManager::closeHandles()
{
if (m_hScripterProcess) { CloseHandle(m_hScripterProcess); m_hScripterProcess = NULL; }
if (m_hDataThread) { CloseHandle(m_hDataThread); m_hDataThread = NULL; }
if (m_hMsgThread) { CloseHandle(m_hMsgThread); m_hMsgThread = NULL; }
if (m_hDataRead != INVALID_HANDLE_VALUE) { CloseHandle(m_hDataRead); m_hDataRead = INVALID_HANDLE_VALUE; }
if (m_hMsgRead != INVALID_HANDLE_VALUE) { CloseHandle(m_hMsgRead); m_hMsgRead = INVALID_HANDLE_VALUE; }
}
bool ScripterManager::start(const wstringi &configName, const wstringi &configPath,
const Symbols &syms, LogLevel logLevel)
{
// If a previous async start is still running, skip
if (m_startFuture.valid() &&
m_startFuture.wait_for(std::chrono::seconds(0)) == std::future_status::timeout)
return false;
m_logLevel.store(logLevel, std::memory_order_relaxed);
m_startFuture = std::async(std::launch::async,
[this, configName, configPath, syms, logLevel]() {
return launchScripter(configName, configPath, syms, logLevel);
});
return true;
}
void ScripterManager::setLogLevel(LogLevel logLevel)
{
m_logLevel.store(logLevel, std::memory_order_relaxed);
std::lock_guard<std::mutex> lock(m_ctrlMutex);
if (!m_ctrlWriter)
return;
try { m_ctrlWriter->writeSetLogLevel(logLevel); } catch (...) {}
// A dropped threshold change is not worth reporting: the scripter keeps
// using the previous one, and the next reload carries the current value.
if (m_ctrlStreambuf && m_ctrlStreambuf->wasBlocked())
m_ctrlStreambuf->clearBlocked();
}
// The value HOME gets when the environment does not already have one.
// USERPROFILE rather than HOMEDRIVE+HOMEPATH: on a domain-joined machine those
// two can point at a network home, which is unreachable while offline - a poor
// thing to hang a configuration search path on. An existing HOME is left
// alone; whoever set it meant it.
//
// Deliberately not published to this process' environment: everything nyamy
// launches (a &ShellExecute target, say) would inherit it. It is handed to the
// scripter only - through its environment block, and through ${HOME} in the ini
// "cmdLine", which is why both go through here.
static std::wstring homeDirectory()
{
wchar_t buf[GANA_MAX_PATH];
DWORD len = GetEnvironmentVariableW(L"HOME", buf, NUMBER_OF(buf));
if (0 < len && len < NUMBER_OF(buf))
return std::wstring(buf, len);
len = GetEnvironmentVariableW(L"USERPROFILE", buf, NUMBER_OF(buf));
if (0 < len && len < NUMBER_OF(buf))
return std::wstring(buf, len);
return std::wstring();
}
// Expand ${VAR} placeholders in s from the environment.
// NYAMY_ROOT / NYAMY_HOME / NYAMY_CONFIG need no special case: NYamyPaths has
// published them to this process' environment already. HOME does: it is not in
// the environment, so it is answered from homeDirectory() instead.
// Unknown vars expand to nothing and are appended to *unknownVars if provided.
// After each expansion, if the result ends with '\' and the next input char is also '\',
// one backslash is consumed to prevent double separators.
static std::wstring expandVars(const std::wstring &s,
std::vector<std::wstring> *unknownVars = nullptr)
{
std::wstring result;
result.reserve(s.size());
for (size_t i = 0; i < s.size(); ) {
if (s[i] == L'$' && i + 1 < s.size() && s[i + 1] == L'{') {
size_t end = s.find(L'}', i + 2);
if (end == std::wstring::npos) { result += s[i++]; continue; }
std::wstring name = s.substr(i + 2, end - i - 2);
{
wchar_t buf[2048];
DWORD len = GetEnvironmentVariableW(name.c_str(), buf, 2048);
std::wstring home;
if (len == 0 && name == L"HOME")
home = homeDirectory();
if (len > 0 && len < 2048) {
result.append(buf, len);
} else if (!home.empty()) {
result.append(home);
} else {
// Expands to nothing, the way a shell treats an unset
// variable. Leaving ${NAME} in place put the literal text
// on the command line, where it ended up as an argument to
// the script.
if (unknownVars) unknownVars->push_back(name);
}
}
i = end + 1;
// Prevent double backslash when expansion ends with '\' and next char is also '\'.
if (!result.empty() && result.back() == L'\\' && i < s.size() && s[i] == L'\\')
++i;
} else {
result += s[i++];
}
}
return result;
}
// Pipe buffer sizes. CreatePipe() used the 4 KB default; the ctrl size is
// stated explicitly because it is the threshold at which ExecUserFunc is
// dropped rather than allowed to stall the engine thread.
static const DWORD kCtrlPipeBufSize = 16 * 1024;
static const DWORD kDataPipeBufSize = 64 * 1024;
static const DWORD kMsgPipeBufSize = 16 * 1024;
static void closePipeHandle(HANDLE *io_h)
{
if (*io_h != INVALID_HANDLE_VALUE) {
CloseHandle(*io_h);
*io_h = INVALID_HANDLE_VALUE;
}
}
// Create one pipe as a named pipe: nyamy owns the server end, the child
// inherits an ordinary synchronous client handle. Named rather than anonymous
// because only a named pipe handle can be opened for overlapped I/O, which is
// what lets a parked reader thread be stopped without killing the scripter.
// The ends nyamy reads are therefore overlapped; the ctrl end it writes is not,
// since PIPE_NOWAIT already keeps that write off the engine thread's back.
// Nothing changes on the child's side, so a foreign scripter launched through
// the ini "cmdLine" setting is unaffected.
//
// Nothing else can connect: the name is unguessable, the create fails outright
// if it is taken (FILE_FLAG_FIRST_PIPE_INSTANCE), only one instance exists, it
// is consumed immediately below, and remote clients are rejected.
static bool createNamedPipePair(bool i_serverReads, DWORD i_bufSize,
HANDLE *o_hServer, HANDLE *o_hClient)
{
*o_hServer = INVALID_HANDLE_VALUE;
*o_hClient = INVALID_HANDLE_VALUE;
DWORD sessionId = 0;
ProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
std::random_device rd; // cryptographically strong on Windows
SECURITY_ATTRIBUTES saInherit = {};
saInherit.nLength = sizeof(saInherit);
saInherit.bInheritHandle = TRUE;
for (int attempt = 0; attempt < 4; ++attempt) {
wchar_t name[128];
swprintf_s(name, L"\\\\.\\pipe\\GANAware\\nyamy\\%u-%u-%08x%08x",
sessionId, GetCurrentProcessId(), rd(), rd());
// the server end is left non-inheritable (no SECURITY_ATTRIBUTES)
HANDLE hServer = CreateNamedPipe(
name,
(i_serverReads ? PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED
: PIPE_ACCESS_OUTBOUND) |
FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT |
PIPE_REJECT_REMOTE_CLIENTS,
1, i_bufSize, i_bufSize, 0, NULL);
if (hServer == INVALID_HANDLE_VALUE)
continue; // name already taken: try another one
// Opening the client end here fills the pipe's only instance, and
// leaves it connected - which is why no ConnectNamedPipe() is needed.
HANDLE hClient = CreateFile(
name, i_serverReads ? GENERIC_WRITE : GENERIC_READ, 0,
&saInherit, OPEN_EXISTING, 0, NULL);
if (hClient == INVALID_HANDLE_VALUE) {
CloseHandle(hServer);
return false;
}
*o_hServer = hServer;
*o_hClient = hClient;
return true;
}
return false;
}
bool ScripterManager::launchScripter(const wstringi &configName,
const wstringi &configPath,
const Symbols &syms,
LogLevel logLevel)
{
// Stop existing scripter if running. This runs on the async start task,
// which ~ScripterManager waits for, so an unbounded wait here would hang
// the UI thread whenever the old scripter is stuck.
if (m_hScripterProcess != NULL) {
sendQuit();
forceStop(kScripterQuitGraceMillisec);
closeHandles();
m_quitSent = false;
}
// ctrl pipe: nyamy (write) -> scripter (read) via inherited handle in NYS_CTRL env var
HANDLE hCtrlRead = INVALID_HANDLE_VALUE;
// data pipe: scripter (write) -> nyamy (read) via inherited handle in NYS_CMD env var
HANDLE hDataWrite = INVALID_HANDLE_VALUE;
// msg pipe: scripter stdout+stderr (write) -> nyamy (read), merged
HANDLE hMsgWrite = INVALID_HANDLE_VALUE;
// NUL device: passed as STARTUPINFO.hStdInput below, but deliberately not
// inheritable, which leaves the child without a usable stdin. That is the
// intent: control travels over its own pipe (NYS_CTRL), so there is nothing
// for stdin to carry and nothing should arrive through it.
HANDLE hNul = INVALID_HANDLE_VALUE;
hNul = CreateFile(L"NUL", GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hNul == INVALID_HANDLE_VALUE ||
!createNamedPipePair(false, kCtrlPipeBufSize, &m_hCtrlWrite, &hCtrlRead) ||
!createNamedPipePair(true, kDataPipeBufSize, &m_hDataRead, &hDataWrite) ||
!createNamedPipePair(true, kMsgPipeBufSize, &m_hMsgRead, &hMsgWrite)) {
if (m_log) {
Acquire a(m_soLog, LogLevel::Error);
*m_log << L"ScripterManager: cannot create pipes" << std::endl;
}
closePipeHandle(&hNul);
closePipeHandle(&hCtrlRead);
closePipeHandle(&hDataWrite);
closePipeHandle(&hMsgWrite);
closePipeHandle(&m_hCtrlWrite);
closePipeHandle(&m_hDataRead);
closePipeHandle(&m_hMsgRead);
return false;
}
// The ini value "cmdLine", if present, is the FULL command line
// (executable plus arguments) used to launch the scripter, so that any
// program speaking the scripter protocol can be substituted. When absent,
// fall back to nyamy-scripter.exe next to nyamy.exe. The script argument
// belongs on the command line either way: the scripter has no default
// script of its own and exits with a usage message without one.
wstringi iniCmdLine;
{
IniFile ini;
ini.read(L"cmdLine", &iniCmdLine);
}
std::wstring cmdLineStr;
if (!iniCmdLine.empty()) {
std::vector<std::wstring> unknownVars;
cmdLineStr = expandVars(iniCmdLine, &unknownVars);
for (const auto &uv : unknownVars) {
if (m_log) {
Acquire a(m_soLog, LogLevel::Warn);
*m_log << L"cmdLine: unknown variable: ${" << uv << L"}" << std::endl;
}
}
} else {
cmdLineStr = L"\"" + NYamyPaths::root() + L"\\nyamy-scripter.exe\" .mayu.rb";
}
// build an environment block that includes NYS_CTRL and NYS_CMD
// so the child receives pipe handle values without polluting the parent environment
wchar_t ctrlVal[32], cmdVal[32];
swprintf_s(ctrlVal, L"%llu",
static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(hCtrlRead)));
swprintf_s(cmdVal, L"%llu",
static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(hDataWrite)));
std::vector<wchar_t> envBlock;
{
auto addVar = [&](const wchar_t *name, const wchar_t *value) {
for (const wchar_t *p = name; *p; ++p) envBlock.push_back(*p);
envBlock.push_back(L'=');
for (const wchar_t *p = value; *p; ++p) envBlock.push_back(*p);
envBlock.push_back(L'\0');
};
addVar(L"NYS_CTRL", ctrlVal);
addVar(L"NYS_CMD", cmdVal);
// The scripter (and a script reading ENV["HOME"]) gets a HOME even when
// Windows did not provide one. Only the scripter does: see
// homeDirectory().
std::wstring home = homeDirectory();
if (!home.empty())
addVar(L"HOME", home.c_str());
// append current process environment
wchar_t *cur = GetEnvironmentStringsW();
if (cur) {
for (const wchar_t *p = cur; *p; ) {
const wchar_t *entry = p;
while (*p) ++p;
++p; // skip NUL
// Skip the entries just written, so each name appears once.
// The length is in characters, not bytes: wcsncmp counts
// wchar_t, and a count past the pattern's NUL makes every
// comparison fail, which would let the old value through.
wchar_t nysCtrlEq[] = L"NYS_CTRL=";
wchar_t nysCmdEq[] = L"NYS_CMD=";
wchar_t homeEq[] = L"HOME=";
bool skip = (wcsncmp(entry, nysCtrlEq, NUMBER_OF(nysCtrlEq) - 1) == 0 ||
wcsncmp(entry, nysCmdEq, NUMBER_OF(nysCmdEq) - 1) == 0 ||
(!home.empty() &&
wcsncmp(entry, homeEq, NUMBER_OF(homeEq) - 1) == 0));
if (!skip) {
for (const wchar_t *q = entry; q < p; ++q) envBlock.push_back(*q);
}
}
FreeEnvironmentStringsW(cur);
}
envBlock.push_back(L'\0'); // final double-NUL terminator
}
STARTUPINFO si = {};
si.cb = sizeof(si);
// FORCEOFFFEEDBACK: a child created while the parent still carries the
// shell's startup feedback inherits it, and the scripter is a console
// process that never pumps messages, so the "app starting" cursor would
// stay up until Windows gives up on it (~5 seconds) - on every start and
// every reload.
si.dwFlags = STARTF_USESTDHANDLES | STARTF_FORCEOFFFEEDBACK;
si.hStdInput = hNul; // stdin = NUL (EOF on read)
si.hStdOutput = hMsgWrite; // stdout = message log
si.hStdError = hMsgWrite; // stderr = same pipe (merged)
PROCESS_INFORMATION pi = {};
// CreateProcess may modify the command line buffer; pass a copy so that
// cmdLineStr stays intact for logging
std::wstring cmdLineBuf = cmdLineStr;
BOOL result = CreateProcess(NULL, cmdLineBuf.data(), NULL, NULL, TRUE,
CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
envBlock.data(), NULL, &si, &pi);
DWORD lastErr = GetLastError();
// close handles that were passed to / used by the child
CloseHandle(hCtrlRead);
CloseHandle(hDataWrite);
CloseHandle(hMsgWrite);
CloseHandle(hNul);
if (!result) {
if (m_log) {
Acquire a(m_soLog, LogLevel::Error);
*m_log << L"ScripterManager: failed to start " << cmdLineStr
<< L" (error " << lastErr << L")" << std::endl;
}
return false;
}
CloseHandle(pi.hThread);
m_hScripterProcess = pi.hProcess;
{
std::lock_guard<std::mutex> lock(m_ctrlMutex);
// construct ctrl write stream
m_ctrlStreambuf = std::make_unique<PipeWriteStreambuf>(m_hCtrlWrite);
m_ctrlStream = std::make_unique<std::ostream>(m_ctrlStreambuf.get());
m_ctrlWriter = std::make_unique<CtrlStreamWriter>(*m_ctrlStream);
// start background threads. A restart above left the stop event set.
ResetEvent(m_hReaderStop);
unsigned tid;
m_hDataThread = (HANDLE)_beginthreadex(NULL, 0, dataThread, this, 0, &tid);
m_hMsgThread = (HANDLE)_beginthreadex(NULL, 0, msgThread, this, 0, &tid);
if (m_log) {
Acquire a(m_soLog, LogLevel::Info);
*m_log << L"ScripterManager: started " << cmdLineStr << std::endl;
}
// Send CtrlId::Start with config name, path, and symbols.
// This runs while the pipe is still blocking, so the (possibly large)
// Start message is delivered reliably before we switch to drop-on-full.
if (m_ctrlWriter) {
try { m_ctrlWriter->writeStart(configName, configPath, syms, logLevel); } catch (...) {}
}
// From now on, ctrl writes (ExecUserFunc from the engine thread) must not
// block if the scripter is busy: drop and log instead of stalling input.
if (m_ctrlStreambuf)
m_ctrlStreambuf->setNonBlocking();
}
return true;
}
void ScripterManager::setExecKeySeqCallback(ExecKeySeqCallback cb)
{
m_execKeySeqCallback = std::move(cb);
}
void ScripterManager::execUserFunc(const wstringi &name,
const std::vector<FuncArg> &args,
const TriggerInfo &ctx)
{
// Called on the engine's keyboard handler thread. The ctrl pipe is in
// non-blocking mode (see launchScripter), so if the scripter is busy and
// the pipe buffer is full this write is dropped rather than stalling all
// key processing. Report the drop instead.
// The lock is what keeps the stream from being destroyed under us:
// sendQuit() resets it from the UI thread.
std::lock_guard<std::mutex> lock(m_ctrlMutex);
if (m_ctrlWriter) {
try { m_ctrlWriter->writeExecUserFunc(name, args, ctx); } catch (...) {}
}
if (m_ctrlStreambuf && m_ctrlStreambuf->wasBlocked()) {
m_ctrlStreambuf->clearBlocked();
if (m_log) {
Acquire a(m_soLog, LogLevel::Warn);
*m_log << L"ScripterManager: ctrl pipe full; discarded "
L"ExecUserFunc(" << name << L")" << std::endl;
}
}
}
//-----------------------------------------------------------------------------
// Background thread: data (CmdStream from scripter stdout)
//-----------------------------------------------------------------------------
unsigned __stdcall ScripterManager::dataThread(void *param)
{
static_cast<ScripterManager *>(param)->runReader();
return 0;
}
void ScripterManager::runReader()
{
PipeReadStreambuf rsb(m_hDataRead, m_hReaderStop);
std::istream pipeStream(&rsb);
CmdStreamReader reader(pipeStream);
CmdProcessor processor(m_soLog, m_log);
processor.onCommit([this](std::shared_ptr<Setting> s) {
// Hand the Setting over through the static single slot and notify with
// an empty payload. If the notification is lost, or superseded by a
// later commit, the Setting is released by the next store or by
// clearPendingSetting() at shutdown - it is never leaked. A failed
// post needs no cleanup for the same reason, so the result is
// intentionally ignored.
setPendingSetting(std::move(s));
PostMessage(m_hwndNotify, WM_ScripterSettingReady, 0, 0);
});
processor.onExecKeySeq([this](AdHocKeySeq item) {
if (m_execKeySeqCallback) m_execKeySeqCallback(std::move(item));
});
processor.process(reader);
}
//-----------------------------------------------------------------------------
// Background thread: msg (log text from scripter stdout+stderr, merged)
//-----------------------------------------------------------------------------
unsigned __stdcall ScripterManager::msgThread(void *param)
{
static_cast<ScripterManager *>(param)->runMsgReader();
return 0;
}
void ScripterManager::runMsgReader()
{
PipeReadStreambuf rsb(m_hMsgRead, m_hReaderStop);
std::istream is(&rsb);
std::string line;
while (std::getline(is, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
// Strip the "{Lev}|" tag the scripter puts in front of every line and
// turn it back into a level. An untagged line is a bare puts from a
// user script (or from the mruby runtime), which counts as info.
LogLevel level = LogLevel::Info;
size_t body = 0;
if (2 <= line.size() && line[1] == '|' &&
logLevelFromChar(static_cast<wchar_t>(line[0]), &level))
body = 2;
std::wstring wline = from_UTF8(line.substr(body));
if (m_log) {
// Filtered again here: the scripter drops what it can, but a line
// written before it saw SetLogLevel is already on its way.
Acquire a(m_soLog, level);
*m_log << L"[scripter] " << wline << std::endl;
}
}
}