forked from directvt/vtm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsrv.hpp
5354 lines (5265 loc) · 206 KB
/
consrv.hpp
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) NetXS Group.
// Licensed under the MIT license.
#pragma once
#if defined(_WIN32)
template<class Term, class Arch>
struct impl;
struct consrv
{
fd_t condrv{ os::invalid_fd }; // consrv: Console driver handle.
fd_t refdrv{ os::invalid_fd }; // consrv: Console driver reference.
fd_t prochndl{ os::invalid_fd };
pidt proc_pid{};
std::thread waitexit; // consrv: The trailing thread for the child process.
virtual si32 wait() = 0;
virtual void undo(bool undo_redo) = 0;
virtual void start() = 0;
virtual void reset() = 0;
virtual fd_t watch() = 0;
virtual bool send(view utf8) = 0;
virtual void keybd(input::hids& gear, bool decckm) = 0;
virtual void mouse(input::hids& gear, bool moved, twod coord, input::mouse::prot encod, input::mouse::mode state) = 0;
virtual void paste(view block) = 0;
virtual void focus(bool state) = 0;
virtual void winsz(twod newsz) = 0;
virtual void style(si32 style) = 0;
virtual void sighup() = 0;
void cleanup(bool io_log)
{
if (waitexit.joinable())
{
if (io_log) log("%%Process waiter joining %%", prompt::vtty, utf::to_hex_0x(waitexit.get_id()));
waitexit.join();
}
}
template<class Term>
static auto create(Term& terminal)
{
auto inst = netxs::sptr<consrv>{};
if (nt::is_wow64()) inst = ptr::shared<impl<Term, ui64>>(terminal);
else inst = ptr::shared<impl<Term, arch>>(terminal);
return inst;
}
template<class Term, class Proc>
auto attach(Term& terminal, eccc cfg, Proc trailer, fdrw fdlink)
{
auto err_code = 0;
auto startinf = STARTUPINFOEXW{ sizeof(STARTUPINFOEXW) };
auto procsinf = PROCESS_INFORMATION{};
auto attrbuff = std::vector<byte>{};
auto attrsize = SIZE_T{ 0 };
condrv = nt::console::handle("\\Device\\ConDrv\\Server");
refdrv = nt::console::handle(condrv, "\\Reference");
auto success = nt::is_wow64() ? nt::ioctl(nt::console::op::set_server_information, condrv, (ui64)watch())
: nt::ioctl(nt::console::op::set_server_information, condrv, (arch)watch());
if (success != ERROR_SUCCESS)
{
os::close(condrv);
os::close(refdrv);
err_code = os::error();
os::fail(prompt::vtty, "Console server creation error");
return err_code;
}
start();
auto handle_count = 3;
if (fdlink)
{
handle_count = 2;
startinf.StartupInfo.hStdInput = fdlink->r;
startinf.StartupInfo.hStdOutput = fdlink->w;
}
else
{
startinf.StartupInfo.hStdInput = nt::console::handle(condrv, "\\Input", true); // Windows8's cmd.exe requires that handles.
startinf.StartupInfo.hStdOutput = nt::console::handle(condrv, "\\Output", true); //
startinf.StartupInfo.hStdError = nt::duplicate(startinf.StartupInfo.hStdOutput); //
}
startinf.StartupInfo.dwX = 0;
startinf.StartupInfo.dwY = 0;
startinf.StartupInfo.dwXCountChars = 0;
startinf.StartupInfo.dwYCountChars = 0;
startinf.StartupInfo.dwXSize = cfg.win.x;
startinf.StartupInfo.dwYSize = cfg.win.y;
startinf.StartupInfo.dwFillAttribute = 1;
startinf.StartupInfo.dwFlags = STARTF_USESTDHANDLES
| STARTF_USESIZE
| STARTF_USEPOSITION
| STARTF_USECOUNTCHARS
| STARTF_USEFILLATTRIBUTE;
::InitializeProcThreadAttributeList(nullptr, 2, 0, &attrsize);
attrbuff.resize(attrsize);
startinf.lpAttributeList = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(attrbuff.data());
::InitializeProcThreadAttributeList(startinf.lpAttributeList, 2, 0, &attrsize);
::UpdateProcThreadAttribute(startinf.lpAttributeList,
0,
PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
&startinf.StartupInfo.hStdInput,
sizeof(startinf.StartupInfo.hStdInput) * handle_count,
nullptr,
nullptr);
::UpdateProcThreadAttribute(startinf.lpAttributeList,
0,
ProcThreadAttributeValue(sizeof("Reference"), faux, true, faux),
&refdrv,
sizeof(refdrv),
nullptr,
nullptr);
auto wcmd = utf::to_utf(cfg.cmd);
auto wcwd = utf::to_utf(cfg.cwd);
auto wenv = utf::to_utf(os::env::add(cfg.env += "VTM=1\0"sv));
auto ret = ::CreateProcessW(nullptr, // lpApplicationName
wcmd.data(), // lpCommandLine
nullptr, // lpProcessAttributes
nullptr, // lpThreadAttributes
TRUE, // bInheritHandles
EXTENDED_STARTUPINFO_PRESENT | // dwCreationFlags (override startupInfo type)
CREATE_UNICODE_ENVIRONMENT, // Environment block in UTF-16.
wenv.data(), // lpEnvironment
wcwd.size() ? wcwd.c_str() // lpCurrentDirectory
: nullptr,
&startinf.StartupInfo, // lpStartupInfo (ptr to STARTUPINFOEX)
&procsinf); // lpProcessInformation
if (!fdlink)
{
os::close(startinf.StartupInfo.hStdInput);
os::close(startinf.StartupInfo.hStdOutput);
os::close(startinf.StartupInfo.hStdError);
}
if (ret == 0)
{
prochndl = { os::invalid_fd };
proc_pid = {};
err_code = os::error();
os::fail(prompt::vtty, "Process creation error");
wait();
}
else
{
os::close( procsinf.hThread );
prochndl = procsinf.hProcess;
proc_pid = procsinf.dwProcessId;
waitexit = std::thread{ [&, trailer]
{
auto pid = proc_pid; // MSVC don't capture it.
io::select(prochndl, [&terminal, pid]{ if (terminal.io_log) log("%%Process %pid% terminated", prompt::vtty, pid); });
trailer();
if (terminal.io_log) log("%%Process %pid% waiter ended", prompt::vtty, pid);
}};
}
return err_code;
}
};
template<class Term, class Arch>
struct impl : consrv
{
using consrv::condrv;
using consrv::refdrv;
static constexpr auto win32prompt = sizeof(Arch) == 4 ? netxs::prompt::nt32 : netxs::prompt::nt64;
//static constexpr auto isreal = requires(Term terminal) { terminal.decstr(); }; // MSVC bug: It doesn't see constexpr value everywehere, even constexpr functions inside lambdas.
static constexpr auto isreal()
{
return requires(Term terminal) { terminal.decstr(); };
}
struct cook
{
wide wstr{};
text ustr{};
view rest{};
ui32 ctrl{};
auto save(bool isutf16)
{
wstr.clear();
utf::to_utf(ustr, wstr);
if (isutf16) rest = { reinterpret_cast<char*>(wstr.data()), wstr.size() * 2 };
else rest = ustr;
}
auto drop()
{
ustr.clear();
wstr.clear();
rest = ustr;
}
};
struct memo
{
size_t seek{};
std::list<std::pair<si32, rich>> undo{};
std::list<std::pair<si32, rich>> redo{};
std::vector<rich> data{};
rich idle{};
auto save(para& line)
{
auto& content = line.content();
if (undo.empty() || !content.same(undo.back().second))
{
undo.emplace_back(line.caret, content);
redo.clear();
}
}
auto swap(para& line, bool back)
{
if (back) std::swap(undo, redo);
if (undo.size())
{
auto& content = line.content();
while (undo.size() && content.same(undo.back().second)) undo.pop_back();
if (undo.size())
{
redo.emplace_back(line.caret, content);
line.content(undo.back().second);
line.caret = undo.back().first;
undo.pop_back();
}
}
if (back) std::swap(undo, redo);
}
auto done(para& line)
{
auto& new_data = line.content();
if (new_data.size().x // Don't save space prefixed commands in history.
&& !new_data.peek(dot_00).isspc()
&& (data.empty() || data.back() != new_data))
{
data.push_back(new_data);
seek = data.size() - 1;
}
undo.clear();
redo.clear();
}
auto& fallback() const
{
if (data.size()) return data[seek];
else return idle;
}
auto roll()
{
if (data.size())
{
if (seek == 0) seek = data.size() - 1;
else seek--;
}
}
auto find(para& line)
{
if (data.empty()) return faux;
auto stop = seek;
auto size = line.caret;
while (!line.substr(0, size).same(data[seek].substr(0, size))
|| line.content() .same(data[seek]))
{
roll();
if (seek == stop) return faux;
}
save(line);
line.content() = data[seek];
line.caret = size;
line.caret_check();
return true;
}
auto deal(para& line, size_t i)
{
if (i < data.size())
{
save(line);
line.content(data[seek = i]);
}
}
auto prev(para& line) { if (seek > 0 && line.content().same(data[seek])) roll();
deal(line, seek ); }
auto pgup(para& line) { deal(line, 0 ); }
auto next(para& line) { deal(line, seek + 1 ); }
auto pgdn(para& line) { deal(line, data.size() - 1); }
};
struct clnt
{
struct hndl
{
enum type
{
unused,
events,
scroll,
altbuf,
};
clnt& boss;
ui32& mode;
type kind;
void* link;
text toUTF8;
text toANSI;
wide toWIDE;
hndl(clnt& boss, ui32& mode, type kind, void* link)
: boss{ boss },
mode{ mode },
kind{ kind },
link{ link }
{ }
friend auto& operator << (std::ostream& s, hndl const& h)
{
if (h.kind == hndl::type::events)
{
s << "events(" << h.mode << ") 0";
if (h.mode & nt::console::inmode::echo ) s << " | ECHO";
if (h.mode & nt::console::inmode::insert ) s << " | INSERT";
if (h.mode & nt::console::inmode::cooked ) s << " | COOKED_READ";
if (h.mode & nt::console::inmode::mouse ) s << " | MOUSE_INPUT";
if (h.mode & nt::console::inmode::preprocess) s << " | PROCESSED_INPUT";
if (h.mode & nt::console::inmode::quickedit ) s << " | QUICK_EDIT";
if (h.mode & nt::console::inmode::winsize ) s << " | WINSIZE";
if (h.mode & nt::console::inmode::vt ) s << " | VIRTUAL_TERMINAL_INPUT";
}
else
{
s << "scroll(" << h.mode << ") 0";
if (h.mode & nt::console::outmode::preprocess ) s << " | PROCESSED_OUTPUT";
if (h.mode & nt::console::outmode::wrap_at_eol) s << " | WRAP_AT_EOL";
if (h.mode & nt::console::outmode::vt ) s << " | VIRTUAL_TERMINAL_PROCESSING";
if (h.mode & nt::console::outmode::no_auto_cr ) s << " | NO_AUTO_CR";
if (h.mode & nt::console::outmode::lvb_grid ) s << " | LVB_GRID_WORLDWIDE";
}
return s;
}
};
struct info
{
ui32 iconid{};
ui32 hotkey{};
ui32 config{};
ui16 colors{};
ui16 format{};
twod scroll{};
rect window{};
bool cliapp{};
bool expose{};
text header{};
text curexe{};
text curdir{};
};
using list = std::list<hndl>;
using bufs = std::list<decltype(Term::altbuf)>;
list tokens; // clnt: Taked handles.
Arch procid; // clnt: Process id.
Arch thread; // clnt: Process thread id.
ui32 pgroup; // clnt: Process group id.
info detail; // clnt: Process details.
cell backup; // clnt: Text attributes to restore on detach.
bufs alters; // clnt: Additional scrollback buffers.
};
using hndl = clnt::hndl;
struct tsid
{
ui32 lo;
ui32 hi;
};
struct base
{
tsid taskid;
Arch client; // clnt*
Arch target; // hndl*
ui32 fxtype;
ui32 packsz;
ui32 echosz;
ui32 pad__1;
};
struct task : base
{
ui32 callfx;
ui32 arglen;
byte argbuf[88 + sizeof(Arch)]; // x64:=96 x32:=92
};
template<class Payload>
struct wrap
{
template<class T>
static auto& cast(T& buffer)
{
static_assert(sizeof(T) >= sizeof(Payload));
return *reinterpret_cast<Payload*>(&buffer);
}
template<class T>
static auto& cast(T* buffer)
{
static_assert(sizeof(T) >= sizeof(Payload));
return *reinterpret_cast<Payload*>(buffer);
}
static auto& cast(text& buffer)
{
buffer.resize(sizeof(Payload));
return *reinterpret_cast<Payload*>(buffer.data());
}
static auto cast(text& buffer, size_t count)
{
buffer.resize(sizeof(Payload) * count);
return std::span{ reinterpret_cast<Payload*>(buffer.data()), count };
}
};
template<class Payload>
struct drvpacket : base, wrap<Payload>
{
ui32 callfx;
ui32 arglen;
};
struct cdrw
{
using stat = NTSTATUS;
struct order
{
tsid taskid;
Arch buffer; // void*
ui32 length;
ui32 offset;
};
tsid taskid;
stat status;
Arch report;
Arch buffer; // void*
ui32 length;
ui32 offset;
auto readoffset() const { return static_cast<ui32>(length ? length + sizeof(ui32) * 2 /*sizeof(drvpacket payload)*/ : 0); }
auto sendoffset() const { return length; }
template<class T>
auto recv_data(fd_t condrv, T&& buffer)
{
auto request = order
{
.taskid = taskid,
.buffer = (Arch)buffer.data(),
.length = static_cast<decltype(order::length)>(buffer.size() * sizeof(buffer.front())),
.offset = readoffset(),
};
auto rc = nt::ioctl(nt::console::op::read_input, condrv, request);
if (rc != ERROR_SUCCESS)
{
if constexpr (debugmode) log("\tAbort reading input (condrv, request) rc=", rc);
status = nt::status::unsuccessful;
return faux;
}
return true;
}
template<bool Complete = faux, class T>
auto send_data(fd_t condrv, T&& buffer, bool inc_nul_terminator = faux)
{
auto result = order
{
.taskid = taskid,
.buffer = (Arch)buffer.data(),
.length = static_cast<decltype(order::length)>((buffer.size() + inc_nul_terminator) * sizeof(buffer.front())),
.offset = sendoffset(),
};
auto rc = nt::ioctl(nt::console::op::write_output, condrv, result);
if (rc != ERROR_SUCCESS)
{
if constexpr (debugmode) log("\tnt::console::op::write_output()", os::unexpected, " ", utf::to_hex(rc));
status = nt::status::unsuccessful;
result.length = 0;
}
report = result.length;
if constexpr (Complete) //Note: Be sure that packet.reply.bytes or count is set.
{
nt::ioctl(nt::console::op::complete_io, condrv, *this);
}
}
auto interrupt(fd_t condrv_handle)
{
status = nt::status::invalid_handle;
nt::ioctl(nt::console::op::complete_io, condrv_handle, *this);
if constexpr (debugmode) log("\tPending operation aborted");
}
};
struct evnt
{
using jobs = generics::jobs<std::tuple<cdrw, Arch /*(hndl*)*/, bool>>;
using lock = std::recursive_mutex;
using sync = std::condition_variable_any;
using vect = std::vector<INPUT_RECORD>;
using irec = INPUT_RECORD;
using work = std::thread;
using cast = std::unordered_map<text, std::unordered_map<text, text>>;
using hist = std::unordered_map<text, memo>;
using mbtn = netxs::input::mouse::hist;
impl& server; // evnt: Console server reference.
vect stream; // evnt: Input event list.
vect recbuf; // evnt: Temporary buffer for copying event records.
sync signal; // evnt: Input event append signal.
lock locker; // evnt: Input event buffer mutex.
cook cooked; // evnt: Cooked input string.
jobs worker; // evnt: Background task executer.
flag closed; // evnt: Console server was shutdown.
fire ondata; // evnt: Signal on input buffer data.
wide wcpair; // evnt: Surrogate pair buffer.
wide toWIDE; // evnt: UTF-16 decoder buffer.
text toUTF8; // evnt: UTF-8 decoder buffer.
text toANSI; // evnt: ANSI decoder buffer.
irec leader; // evnt: Hanging key event record (lead byte).
work ostask; // evnt: Console task thread for the child process.
bool ctrl_c; // evnt: Ctrl+C was pressed.
cast macros; // evnt: Doskey macros storage.
hist inputs; // evnt: Input history per process name storage.
mbtn dclick; // evnt: Mouse double-click tracker.
si32 mstate; // evnt: Mouse button last state.
evnt(impl& serv)
: server{ serv },
closed{ faux },
leader{ },
ctrl_c{ faux },
mstate{ }
{ }
auto& ref_history(text& exe)
{
return inputs[utf::to_low(exe)];
}
auto get_history(text& exe)
{
auto lock = std::lock_guard{ locker };
auto crop = text{};
auto iter = inputs.find(utf::to_low(exe));
if (iter != inputs.end())
{
auto& recs = iter->second;
for (auto& rec : recs.data)
{
crop += rec.utf8();
crop += '\0';
}
}
return crop;
}
void off_history(text& exe)
{
auto lock = std::lock_guard{ locker };
auto iter = inputs.find(utf::to_low(exe));
if (iter != inputs.end()) inputs.erase(iter);
}
void add_alias(text& exe, text& src, text& dst)
{
auto lock = std::lock_guard{ locker };
if (exe.size() && src.size())
{
utf::to_low(exe);
utf::to_low(src);
if (dst.size())
{
macros[exe][src] = dst;
}
else
{
if (auto exe_iter = macros.find(exe); exe_iter != macros.end())
{
auto& src_map = exe_iter->second;
if (auto src_iter = src_map.find(src); src_iter != src_map.end())
{
src_map.erase(src_iter);
}
if (src_map.empty())
{
macros.erase(exe_iter);
}
}
}
}
}
auto get_alias(text& exe, text& src)
{
auto lock = std::lock_guard{ locker };
auto crop = text{};
if (exe.size() && src.size())
{
utf::to_low(exe);
utf::to_low(src);
if (auto exe_iter = macros.find(exe); exe_iter != macros.end())
{
auto& src_map = exe_iter->second;
if (auto src_iter = src_map.find(src); src_iter != src_map.end())
{
crop = src_iter->second;
}
}
}
return crop;
}
auto get_exes()
{
auto lock = std::lock_guard{ locker };
auto crop = text{};
for (auto& [exe, map] : macros)
{
crop += exe;
crop += '\0';
}
return crop;
}
auto get_aliases(text& exe)
{
auto lock = std::lock_guard{ locker };
auto crop = text{};
utf::to_low(exe);
if (auto exe_iter = macros.find(exe); exe_iter != macros.end())
{
auto& src_map = exe_iter->second;
for (auto& [key, val] : src_map)
{
crop += key;
crop += '=';
crop += val;
crop += '\0';
}
}
return crop;
}
void map_cd_shim(text& exe, text& line)
{
static constexpr auto cd_prefix = "cd "sv;
static constexpr auto cd_forced = "cd/d ";
auto shadow = qiew{ line };
utf::trim_front(shadow);
if (exe.starts_with("cmd")
&& shadow.size() > cd_prefix.size()
&& shadow.back() != '\t')
{
auto prefix = shadow.substr(0, 3).str();
utf::to_low(prefix);
if (prefix != cd_prefix) return;
auto crop = shadow.substr(cd_prefix.size());
auto path = crop;
utf::trim_front(path, " \t\r\n");
if (path && path.front() != '/')
{
line = cd_forced + crop.str();
}
}
}
void map_aliases(text& exe, text& line)
{
if (macros.empty() || line.empty()) return;
utf::to_low(exe);
auto exe_iter = macros.find(exe);
if (exe_iter == macros.end()) return;
auto& src_map = exe_iter->second;
if (src_map.empty()) return;
auto rest = qiew{ line };
auto crop = utf::get_tail<faux>(rest, " \r\n");
auto iter = src_map.find(utf::to_low(crop));
if (iter == src_map.end()) return;
auto tail = utf::trim_back(rest, "\r\n");
auto args = utf::split<true>(rest, ' ');
auto data = qiew{ iter->second };
auto result = text{};
while (data)
{
result += utf::get_tail<faux>(data, "$");
if (data.size() >= 2)
{
auto s = utf::pop_front(data, 2);
auto c = utf::to_low(s.back());
if (c >= '1' && c <= '9')
{
auto n = static_cast<ui32>(c - '1');
if (args.size() > n) result += args[n];
}
else switch (c)
{
case '$': result += '$'; break;
case 'g': result += '>'; break;
case 'l': result += '<'; break;
case 't': result += '&'; break;
case 'b': result += '|'; break;
case '*': result += rest; break;
default: result += s; break;
}
}
}
result += tail;
line = result;
}
auto off_aliases(text& exe)
{
auto lock = std::lock_guard{ locker };
utf::to_low(exe);
if (auto exe_iter = macros.find(exe); exe_iter != macros.end())
{
macros.erase(exe_iter);
}
}
void reset()
{
auto lock = std::lock_guard{ locker };
closed.exchange(faux);
stream.clear();
ondata.flush();
}
auto count()
{
auto lock = std::lock_guard{ locker };
return static_cast<ui32>(stream.size());
}
void abort(hndl* handle_ptr)
{
auto target_ref = (Arch)handle_ptr;
auto lock = std::lock_guard{ locker };
worker.cancel([&](auto& token)
{
auto& answer = std::get<0>(token);
auto& target = std::get<1>(token);
auto& cancel = std::get<2>(token);
if (target == target_ref)
{
cancel = true;
answer.interrupt(server.condrv);
}
});
signal.notify_all();
}
void alert(ui32 what, ui32 pgroup = 0)
{
static auto index = 0;
if (server.io_log) log(server.prompt, "ConsoleTask event index ", ++index);
if (ostask.joinable()) ostask.join();
ostask = std::thread{ [what, pgroup, io_log = server.io_log, joined = server.joined, prompt = escx{ server.prompt }]() mutable
{
if (io_log) prompt.add(what == os::signals::ctrl_c ? "Ctrl+C"
: what == os::signals::ctrl_break ? "Ctrl+Break"
: what == os::signals::close ? "Ctrl Close"
: what == os::signals::logoff ? "Ctrl Logoff"
: what == os::signals::shutdown ? "Ctrl Shutdown"
: "Unknown", " event index ", index);
for (auto& client : joined)
{
if (!pgroup || pgroup == client.pgroup)
{
auto stat = nt::ConsoleTask<Arch>(client.procid, what);
if (io_log) prompt.add("\n\tclient process ", client.procid, ", control status ", utf::to_hex_0x(stat));
}
}
if (io_log) log("", prompt, "\n\t-------------------------");
}};
}
void sighup()
{
auto lock = std::lock_guard{ locker };
alert(CTRL_CLOSE_EVENT);
}
void stop()
{
if (ostask.joinable()) ostask.join();
auto lock = std::unique_lock{ locker };
closed.exchange(true);
signal.notify_all();
}
void clear()
{
auto lock = std::lock_guard{ locker };
ondata.flush();
stream.clear();
recbuf.clear();
cooked.drop();
}
auto generate(wchr ch, si32 st = 0, si32 vc = 0, si32 dn = 1, si32 sc = 0)
{
stream.emplace_back(INPUT_RECORD
{
.EventType = KEY_EVENT,
.Event =
{
.KeyEvent =
{
.bKeyDown = dn,
.wRepeatCount = 1,
.wVirtualKeyCode = (ui16)vc,
.wVirtualScanCode = (ui16)sc,
.uChar = { .UnicodeChar = ch },
.dwControlKeyState = (ui32)st,
}
}
});
return true;
}
auto generate(wchr c1, wchr c2)
{
generate(c1);
generate(c2);
return true;
}
auto generate(wiew wstr, si32 s = 0)
{
stream.reserve(wstr.size());
auto head = wstr.begin();
auto tail = wstr.end();
//auto noni = server.inpmod & nt::console::inmode::preprocess; // `-NonInteractive` powershell mode.
while (head != tail)
{
auto c = *head++;
if (c == '\r')
{
if (head != tail && *head == '\n') head++; // Eat CR+LF.
generate('\r', s, VK_RETURN, 1, 0x1c); // Emulate Enter.
// Far Manager treats Shift+Enter as its own macro not a soft break.
//if (noni) generate('\n', s);
//else generate('\r', s | SHIFT_PRESSED, VK_RETURN, 1, 0x1c /*os::nt::takevkey<VK_RETURN>().key*/); // Emulate hitting Enter. Pressed Shift to soft line break when pasting from clipboard.
}
else if (c == '\n')
{
if (head != tail && *head == '\r') head++; // Eat LF+CR.
generate('\n', s | LEFT_CTRL_PRESSED, VK_RETURN, 1, 0x1c); // Emulate Shift+Enter.
}
else
{
generate(c, s);
}
}
return true;
}
auto generate(view ustr)
{
toWIDE.clear();
utf::to_utf(ustr, toWIDE);
return generate(toWIDE);
}
void paste(view block)
{
auto lock = std::lock_guard{ locker };
if (server.inpmod & nt::console::inmode::vt && server.uiterm.bpmode) // Paste binary immutable block.
{
auto keys = INPUT_RECORD{ .EventType = KEY_EVENT, .Event = { .KeyEvent = { .bKeyDown = 1, .wRepeatCount = 1 }}};
toWIDE.clear();
utf::to_utf(ansi::paste_begin, toWIDE);
utf::to_utf(block, toWIDE);
utf::to_utf(ansi::paste_end, toWIDE);
for (auto c : toWIDE)
{
keys.Event.KeyEvent.uChar.UnicodeChar = c;
stream.emplace_back(keys);
}
}
else
{
generate(block);
}
signal.notify_one();
ondata.reset();
return;
//todo pwsh is not yet ready for block-pasting (VK_RETURN conversion is required)
//auto data = INPUT_RECORD{ .EventType = MENU_EVENT };
//auto keys = INPUT_RECORD{ .EventType = KEY_EVENT, .Event = { .KeyEvent = { .bKeyDown = 1, .wRepeatCount = 1 }}};
//toWIDE.clear();
//utf::to_utf(block, toWIDE);
//stream.reserve(stream.size() + toWIDE.size() + 2);
//data.Event.MenuEvent.dwCommandId = nt::console::event::custom | nt::console::event::paste_begin;
//stream.emplace_back(data);
//for (auto c : toWIDE)
//{
// keys.Event.KeyEvent.uChar.UnicodeChar = c;
// stream.emplace_back(keys);
//}
//data.Event.MenuEvent.dwCommandId = nt::console::event::custom | nt::console::event::paste_end;
//stream.emplace_back(data);
//ondata.reset();
//signal.notify_one();
}
auto write(view ustr)
{
auto lock = std::lock_guard{ locker };
generate(ustr);
if (!stream.empty())
{
ondata.reset();
signal.notify_one();
}
}
void focus(bool state)
{
auto lock = std::lock_guard{ locker };
auto data = INPUT_RECORD{ .EventType = FOCUS_EVENT };
data.Event.FocusEvent.bSetFocus = state;
stream.emplace_back(data);
ondata.reset();
signal.notify_one();
}
void style(si32 format)
{
auto lock = std::lock_guard{ locker };
auto data = INPUT_RECORD{ .EventType = MENU_EVENT };
data.Event.MenuEvent.dwCommandId = nt::console::event::custom | nt::console::event::style;
stream.emplace_back(data);
data.Event.MenuEvent.dwCommandId = nt::console::event::custom | format;
stream.emplace_back(data);
ondata.reset();
signal.notify_one();
}
void mouse(input::hids& gear, bool moved, twod coord)
{
auto state = os::nt::ms_kbstate(gear.ctlstate);
auto bttns = gear.m_sys.buttons & 0b00011111;
auto flags = ui32{};
if (moved) flags |= MOUSE_MOVED;
for (auto i = 0_sz; i < dclick.size(); i++)
{
auto prvbtn = mstate & (1 << i);
auto sysbtn = bttns & (1 << i);
if (prvbtn != sysbtn && sysbtn) // MS UX guidelines recommend signaling a double-click when the button is pressed twice rather than when it is released twice.
{
auto& s = dclick[i];
auto fired = gear.m_sys.timecod;
if (fired - s.fired < gear.delay && s.coord == coord) // Set the double-click flag if the delay has not expired and the mouse is in the same position.
{
flags |= DOUBLE_CLICK;
s.fired = {};
}
else
{
s.fired = fired;
s.coord = coord;
}
}
}
mstate = bttns;
if (gear.m_sys.wheeldt)
{
if (gear.m_sys.wheeled) flags |= MOUSE_WHEELED;
else if (gear.m_sys.hzwheel) flags |= MOUSE_HWHEELED;
bttns |= gear.m_sys.wheeldt << 16;
}
auto lock = std::lock_guard{ locker };
stream.emplace_back(INPUT_RECORD
{
.EventType = MOUSE_EVENT,
.Event =
{
.MouseEvent =
{
.dwMousePosition =
{
.X = (si16)std::clamp<si32>(coord.x, 0, si16max),
.Y = (si16)std::clamp<si32>(coord.y, 0, si16max),
},
.dwButtonState = (DWORD)bttns,
.dwControlKeyState = state,
.dwEventFlags = flags,
}
}
});
ondata.reset();
signal.notify_one();
}
void winsz(twod winsize)
{
auto lock = std::lock_guard{ locker };
stream.emplace_back(INPUT_RECORD // Ignore ENABLE_WINDOW_INPUT - we only signal a viewport change.
{
.EventType = WINDOW_BUFFER_SIZE_EVENT,
.Event =
{
.WindowBufferSizeEvent =
{
.dwSize =
{
.X = (si16)std::min<si32>(winsize.x, si16max),
.Y = (si16)std::min<si32>(winsize.y, si16max),
}
}
}
});
ondata.reset();
signal.notify_one();
}
template<char C>