Debian Codegraph @

components/virtualterminal/source/win/vtemupty.pas

raw
1 {
2 Double Commander
3 -------------------------------------------------------------------------
4 Windows pseudoterminal device implementation
5
6 Copyright (C) 2021 Alexander Koblov ([email protected])
7
8 Permission is hereby granted, free of charge, to any person obtaining
9 a copy of this software and associated documentation files (the
10 "Software"), to deal in the Software without restriction, including
11 without limitation the rights to use, copy, modify, merge, publish,
12 distribute, sublicense, and/or sell copies of the Software, and to
13 permit persons to whom the Software is furnished to do so, subject to
14 the following conditions:
15
16 The above copyright notice and this permission notice shall be included
17 in all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
23 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 }
27
28 unit VTEmuPty;
29
30 {$mode delphi}
31
32 interface
33
34 uses
35 Classes, SysUtils, LCLProc, LCLType, Windows, VTEmuCtl;
36
37 type
38
39 { TPtyDevice }
40
41 TPtyDevice = class(TCustomPtyDevice)
42 private
43 FPty: PVOID;
44 FSize: TCoord;
45 FLength: Integer;
46 FThread: TThread;
47 FPipeIn, FPipeOut: THandle;
48 FBuffer: array[0..8191] of AnsiChar;
49 protected
50 procedure ReadySync;
51 procedure ReadThread;
52 procedure DestroyPseudoConsole;
53 procedure SetConnected(AValue: Boolean); override;
54 function CreatePseudoConsole(const ACommand: String): Boolean;
55 public
56 constructor Create(AOwner: TComponent); override;
57 destructor Destroy; override;
58 function WriteStr(const Str: string): Integer; override;
59 function SetCurrentDir(const Path: String): Boolean; override;
60 function SetScreenSize(aCols, aRows: Integer): Boolean; override;
61 end;
62
63 implementation
64
65 uses
66 CTypes, DCOSUtils, DCConvertEncoding;
67
68 type
69 TConsoleType = (ctNone, ctNative, ctEmulate);
70
71 var
72 ConsoleType: TConsoleType = ctNone;
73
74 procedure ClosePipe(var AHandle: THandle);
75 begin
76 if (AHandle <> INVALID_HANDLE_VALUE) then
77 begin
78 CloseHandle(AHandle);
79 AHandle:= INVALID_HANDLE_VALUE;
80 end;
81 end;
82
83 {
84 *******************************************************************************
85 Windows Pseudo Console (ConPTY), Windows 10 1809 and higher
86 *******************************************************************************
87 }
88
89 const
90 EXTENDED_STARTUPINFO_PRESENT = $00080000;
91 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE = $00020016;
92
93 type
94 PHPCON = ^HPCON;
95 HPCON = type PVOID;
96 SIZE_T = type ULONG_PTR;
97 PSIZE_T = type PULONG_PTR;
98 LPPROC_THREAD_ATTRIBUTE_LIST = type PVOID;
99
100 STARTUPINFOEXW = record
101 StartupInfo: STARTUPINFOW;
102 lpAttributeList: LPPROC_THREAD_ATTRIBUTE_LIST;
103 end;
104
105 var
106 CreatePseudoConsole: function(size: COORD; hInput: HANDLE; hOutput: HANDLE;
107 dwFlags: DWORD; phPC: PHPCON): HRESULT; stdcall;
108 ClosePseudoConsole: procedure(hPC: HPCON); stdcall;
109 ResizePseudoConsole: function(hPC: HPCON; size: COORD): HRESULT; stdcall;
110 InitializeProcThreadAttributeList: function(lpAttributeList: LPPROC_THREAD_ATTRIBUTE_LIST;
111 dwAttributeCount: DWORD; dwFlags: DWORD;
112 lpSize: PSIZE_T): BOOL; stdcall;
113 UpdateProcThreadAttribute: function(lpAttributeList: LPPROC_THREAD_ATTRIBUTE_LIST;
114 dwFlags: DWORD; Attribute: DWORD_PTR;
115 lpValue: PVOID; cbSize: SIZE_T;
116 lpPreviousValue: PVOID; lpReturnSize: PSIZE_T): BOOL; stdcall;
117 DeleteProcThreadAttributeList: procedure(lpAttributeList: LPPROC_THREAD_ATTRIBUTE_LIST); stdcall;
118
119 function CreatePseudoConsoleNew(const ACommand: String; phPC: PPointer; phPipeIn, phPipeOut: PHandle; ASize: COORD): Boolean;
120 var
121 attrListSize: SIZE_T = 0;
122 startupInfo: STARTUPINFOEXW;
123 piClient: PROCESS_INFORMATION;
124 hPipePTYIn: HANDLE = INVALID_HANDLE_VALUE;
125 hPipePTYOut: HANDLE = INVALID_HANDLE_VALUE;
126 begin
127 startupInfo:= Default(STARTUPINFOEXW);
128 Result:= CreatePipe(hPipePTYIn, phPipeOut^, nil, 0) and
129 CreatePipe(phPipeIn^, hPipePTYOut, nil, 0);
130 if Result then
131 begin
132 Result:= CreatePseudoConsole(ASize, hPipePTYIn, hPipePTYOut, 0, phPC) = S_OK;
133 // We can close the handles here because they are duplicated in the ConHost
134 if Result then
135 begin
136 CloseHandle(hPipePTYIn);
137 CloseHandle(hPipePTYOut);
138 hPipePTYIn:= INVALID_HANDLE_VALUE;
139 hPipePTYOut:=INVALID_HANDLE_VALUE;
140 end;
141 end;
142 if Result then
143 begin
144 startupInfo.StartupInfo.cb:= SizeOf(STARTUPINFOEXW);
145 InitializeProcThreadAttributeList(nil, 1, 0, @attrListSize);
146 startupInfo.lpAttributeList:= GetMem(attrListSize);
147 Result:= Assigned(startupInfo.lpAttributeList);
148 if Result then
149 begin
150 // Initialize thread attribute list and set Pseudo Console attribute
151 Result:= InitializeProcThreadAttributeList(startupInfo.lpAttributeList, 1, 0, @attrListSize) and
152 UpdateProcThreadAttribute(startupInfo.lpAttributeList,0,
153 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
154 phPC^, SizeOf(HPCON), nil, nil);
155 end;
156 end;
157 if Result then
158 begin
159 Result:= CreateProcessW(nil, PWideChar(CeUtf8ToUtf16(ACommand)),
160 nil, nil, False, EXTENDED_STARTUPINFO_PRESENT,
161 nil, nil, @startupInfo.StartupInfo, @piClient);
162 end;
163 if not Result then
164 begin
165 ClosePipe(phPipeIn^);
166 ClosePipe(phPipeOut^);
167 ClosePipe(hPipePTYIn);
168 ClosePipe(hPipePTYOut);
169 end;
170 // Cleanup attribute list
171 if Assigned(startupInfo.lpAttributeList) then
172 begin
173 DeleteProcThreadAttributeList(startupInfo.lpAttributeList);
174 FreeMem(startupInfo.lpAttributeList);
175 end;
176 end;
177
178 function InitializeNew: Boolean;
179 var
180 hModule: HINST;
181 begin
182 Result:= (Win32MajorVersion >= 10);
183 if Result then
184 begin
185 hModule:= GetModuleHandle(Kernel32);
186 CreatePseudoConsole:= GetProcAddress(hModule, 'CreatePseudoConsole');
187 Result:= Assigned(CreatePseudoConsole);
188 if Result then
189 begin
190 ClosePseudoConsole:= GetProcAddress(hModule, 'ClosePseudoConsole');
191 ResizePseudoConsole:= GetProcAddress(hModule, 'ResizePseudoConsole');
192 UpdateProcThreadAttribute:= GetProcAddress(hModule, 'UpdateProcThreadAttribute');
193 DeleteProcThreadAttributeList:= GetProcAddress(hModule, 'DeleteProcThreadAttributeList');
194 InitializeProcThreadAttributeList:= GetProcAddress(hModule, 'InitializeProcThreadAttributeList');
195 end;
196 end;
197 end;
198
199 {
200 *******************************************************************************
201 WinPTY
202 *******************************************************************************
203 }
204
205 const
206 WINPTY_MOUSE_MODE_AUTO = 1;
207 WINPTY_MOUSE_MODE_FORCE = 2;
208 // Agent RPC call: process creation
209 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN = 1;
210 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN = 2;
211 // Configuration of a new agent
212 WINPTY_FLAG_CONERR = $01;
213 WINPTY_FLAG_PLAIN_OUTPUT = $02;
214 WINPTY_FLAG_COLOR_ESCAPES = $04;
215 WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION = $08;
216 // Error codes
217 WINPTY_ERROR_SUCCESS = 0;
218 WINPTY_ERROR_OUT_OF_MEMORY = 1;
219 WINPTY_ERROR_SPAWN_CREATE_PROCESS_FAILED = 2;
220 WINPTY_ERROR_LOST_CONNECTION = 3;
221 WINPTY_ERROR_AGENT_EXE_MISSING = 4;
222 WINPTY_ERROR_UNSPECIFIED = 5;
223 WINPTY_ERROR_AGENT_DIED = 6;
224 WINPTY_ERROR_AGENT_TIMEOUT = 7;
225 WINPTY_ERROR_AGENT_CREATION_FAILED = 8;
226
227 type
228 winpty_t = record end;
229 Pwinpty_t = ^winpty_t;
230
231 winpty_result_t = type DWORD;
232
233 winpty_config_t = record end;
234 Pwinpty_config_t = ^winpty_config_t;
235
236 winpty_error_t = record end;
237 winpty_error_ptr_t = ^winpty_error_t;
238 Pwinpty_error_ptr_t = ^winpty_error_ptr_t;
239
240 winpty_spawn_config_t = record end;
241 Pwinpty_spawn_config_t = ^winpty_spawn_config_t;
242
243 var
244 winpty_config_new: function(agentFlags: UInt64; err: Pwinpty_error_ptr_t): Pwinpty_config_t; cdecl;
245 winpty_config_free: procedure(cfg: Pwinpty_config_t); cdecl;
246
247 winpty_config_set_initial_size: procedure(cfg: Pwinpty_config_t; cols, rows: cint); cdecl;
248 winpty_config_set_mouse_mode: procedure(cfg: Pwinpty_config_t; mouseMode: cint); cdecl;
249
250 winpty_open: function(const cfg: Pwinpty_config_t; err: Pwinpty_error_ptr_t): Pwinpty_t; cdecl;
251 winpty_free: procedure(wp: Pwinpty_t); cdecl;
252
253 winpty_error_code: function(err: winpty_error_ptr_t): winpty_result_t; cdecl;
254 winpty_error_msg: function(err: winpty_error_ptr_t): LPCWSTR; cdecl;
255 winpty_error_free: procedure(err: winpty_error_ptr_t); cdecl;
256
257 winpty_spawn_config_new: function(spawnFlags: UInt64; appname, cmdline, cwd,
258 env: LPCWSTR; err: Pwinpty_error_ptr_t): Pwinpty_spawn_config_t; cdecl;
259 winpty_spawn_config_free: procedure(cfg: Pwinpty_spawn_config_t); cdecl;
260
261 winpty_spawn: function(wp: Pwinpty_t; const cfg: Pwinpty_spawn_config_t;
262 process_handle, thread_handle: PHandle;
263 create_process_error: PDWORD; err: Pwinpty_error_ptr_t): BOOL; cdecl;
264
265 winpty_set_size: function(wp: Pwinpty_t; cols, rows: cint; err: Pwinpty_error_ptr_t): BOOL; cdecl;
266
267 winpty_conin_name: function(wp: Pwinpty_t): LPCWSTR; cdecl;
268 winpty_conout_name: function(wp: Pwinpty_t): LPCWSTR; cdecl;
269 winpty_conerr_name: function(wp: Pwinpty_t): LPCWSTR; cdecl;
270
271 function CreatePseudoConsoleOld(const ACommand: String; phPC: PPointer; phPipeIn, phPipeOut: PHandle; ASize: COORD): Boolean;
272 var
273 childHandle: HANDLE;
274 lastError: DWORD = 0;
275 agentCfg: Pwinpty_config_t;
276 spawnCfg: Pwinpty_spawn_config_t;
277 agentFlags: DWORD = WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION;
278 begin
279 // SetEnvironmentVariableW('WINPTY_SHOW_CONSOLE', '1');
280 agentCfg:= winpty_config_new(agentFlags, nil);
281 Result:= Assigned(agentCfg);
282 if Result then
283 begin
284 winpty_config_set_initial_size(agentCfg, ASize.X, ASize.Y);
285
286 phPC^:= winpty_open(agentCfg, nil);
287
288 Result:= Assigned(phPC^);
289
290 winpty_config_free(agentCfg);
291
292 if Result then
293 begin
294 phPipeIn^:= CreateFileW(winpty_conout_name(phPC^), GENERIC_READ, 0, nil, OPEN_EXISTING, 0, 0);
295 phPipeOut^:= CreateFileW(winpty_conin_name(phPC^), GENERIC_WRITE, 0, nil, OPEN_EXISTING, 0, 0);
296
297 spawnCfg:= winpty_spawn_config_new(WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN,
298 nil, PWideChar(CeUtf8ToUtf16(ACommand)), nil, nil, nil);
299 Result:= Assigned(spawnCfg);
300 if Result then
301 begin
302 Result:= winpty_spawn(phPC^, spawnCfg, @childHandle, nil, @lastError, nil);
303 winpty_spawn_config_free(spawnCfg);
304 end;
305
306 if not Result then
307 begin
308 ClosePipe(phPipeIn^);
309 ClosePipe(phPipeOut^);
310 winpty_free(phPC^);
311 end;
312 end;
313 end;
314 end;
315
316 var
317 libwinpty: HINST;
318
319 function InitializeOld: Boolean;
320 begin
321 libwinpty:= LoadLibrary('winpty.dll');
322 Result:= (libwinpty <> 0);
323 if Result then
324 begin
325 winpty_config_new:= GetProcAddress(libwinpty, 'winpty_config_new');
326 winpty_config_free:= GetProcAddress(libwinpty, 'winpty_config_free');
327
328 winpty_config_set_initial_size:= GetProcAddress(libwinpty, 'winpty_config_set_initial_size');
329 winpty_config_set_mouse_mode:= GetProcAddress(libwinpty, 'winpty_config_set_mouse_mode');
330
331 winpty_open:= GetProcAddress(libwinpty, 'winpty_open');
332 winpty_free:= GetProcAddress(libwinpty, 'winpty_free');
333
334 winpty_error_code:= GetProcAddress(libwinpty, 'winpty_error_code');
335 winpty_error_msg:= GetProcAddress(libwinpty, 'winpty_error_msg');
336 winpty_error_free:= GetProcAddress(libwinpty, 'winpty_error_free');
337
338 winpty_spawn_config_new:= GetProcAddress(libwinpty, 'winpty_spawn_config_new');
339 winpty_spawn_config_free:= GetProcAddress(libwinpty, 'winpty_spawn_config_free');
340
341 winpty_spawn:= GetProcAddress(libwinpty, 'winpty_spawn');
342 winpty_set_size:= GetProcAddress(libwinpty, 'winpty_set_size');
343
344 winpty_conin_name:= GetProcAddress(libwinpty, 'winpty_conin_name');
345 winpty_conout_name:= GetProcAddress(libwinpty, 'winpty_conout_name');
346 winpty_conerr_name:= GetProcAddress(libwinpty, 'winpty_conerr_name');
347 end;
348 end;
349
350 { TPtyDevice }
351
352 procedure TPtyDevice.SetConnected(AValue: Boolean);
353 var
354 AShell: String;
355 begin
356 if FConnected = AValue then Exit;
357 FConnected:= AValue;
358
359 if FConnected then
360 begin
361 AShell:= mbGetEnvironmentVariable('ComSpec');
362 if Length(AShell) = 0 then AShell:= 'cmd.exe';
363 FConnected:= CreatePseudoConsole(AShell);
364 if FConnected then
365 begin
366 FThread:= TThread.ExecuteInThread(ReadThread);
367 end;
368 end
369 else begin
370 DestroyPseudoConsole;
371 end;
372 end;
373
374 procedure TPtyDevice.ReadySync;
375 begin
376 if Assigned(FOnRxBuf) then
377 FOnRxBuf(Self, FBuffer, FLength);
378 end;
379
380 procedure TPtyDevice.ReadThread;
381 begin
382 while FConnected do
383 begin
384 FLength:= FileRead(FPipeIn, FBuffer, SizeOf(FBuffer));
385
386 if (FLength > 0) then
387 begin
388 TThread.Synchronize(nil, ReadySync);
389 end;
390 end;
391 end;
392
393 procedure TPtyDevice.DestroyPseudoConsole;
394 begin
395 case ConsoleType of
396 ctNative: ClosePseudoConsole(FPty);
397 ctEmulate: winpty_free(FPty);
398 end;
399 FPty:= nil;
400 ClosePipe(FPipeIn);
401 ClosePipe(FPipeOut);
402 end;
403
404 function TPtyDevice.CreatePseudoConsole(const ACommand: String): Boolean;
405 begin
406 case ConsoleType of
407 ctNative: Result:= CreatePseudoConsoleNew(ACommand, @FPty, @FPipeIn, @FPipeOut, FSize);
408 ctEmulate: Result:= CreatePseudoConsoleOld(ACommand, @FPty, @FPipeIn, @FPipeOut, FSize);
409 ctNone: Result:= False;
410 end;
411 end;
412
413 constructor TPtyDevice.Create(AOwner: TComponent);
414 begin
415 inherited Create(AOwner);
416
417 FSize.X:= 80;
418 FSize.Y:= 25;
419 FPipeIn:= INVALID_HANDLE_VALUE;
420 FPipeOut:= INVALID_HANDLE_VALUE;
421 end;
422
423 destructor TPtyDevice.Destroy;
424 begin
425 inherited Destroy;
426 SetConnected(False);
427 end;
428
429 function TPtyDevice.SetCurrentDir(const Path: String): Boolean;
430 begin
431 Result:= WriteStr('cd /D "' + Path + '"' + #13#10) > 0;
432 end;
433
434 function TPtyDevice.WriteStr(const Str: string): Integer;
435 begin
436 Result:= FileWrite(FPipeOut, Pointer(Str)^, Length(Str));
437 end;
438
439 function TPtyDevice.SetScreenSize(aCols, aRows: Integer): Boolean;
440 var
441 ASize: TCoord;
442 begin
443 if (FPty = nil) then Exit(False);
444
445 if (ConsoleType = ctEmulate) then
446 begin
447 Result:= winpty_set_size(FPty, aCols, aRows, nil);
448 end
449 else if (ConsoleType = ctNative) then
450 begin
451 ASize.Y:= aRows;
452 ASize.X:= aCols;
453 Result:= Succeeded(ResizePseudoConsole(FPty, ASize));
454 end;
455 if Result then
456 begin
457 FSize.Y:= aRows;
458 FSize.X:= aCols;
459 end;
460 end;
461
462 procedure Initialize;
463 begin
464 if InitializeNew then
465 ConsoleType:= ctNative
466 else if InitializeOld then
467 ConsoleType:= ctEmulate;
468 end;
469
470 initialization
471 Initialize;
472
473 end.
474