forked from kenjinote/cmdchat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSource.cpp
493 lines (481 loc) · 13.8 KB
/
Source.cpp
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
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#include <windows.h>
#include <atlbase.h>
#include <atlhost.h>
#include <string>
#include <winternl.h>
#include "resource.h"
#define DEFAULT_DPI 96
#define SCALEX(X) MulDiv(X, uDpiX, DEFAULT_DPI)
#define SCALEY(Y) MulDiv(Y, uDpiY, DEFAULT_DPI)
#define POINT2PIXEL(PT) MulDiv(PT, uDpiY, 72)
TCHAR szClassName[] = TEXT("Window");
BOOL GetScaling(HWND hWnd, UINT* pnX, UINT* pnY)
{
BOOL bSetScaling = FALSE;
const HMONITOR hMonitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST);
if (hMonitor)
{
HMODULE hShcore = LoadLibraryW(L"SHCORE");
if (hShcore)
{
typedef HRESULT __stdcall GetDpiForMonitor(HMONITOR, int, UINT*, UINT*);
GetDpiForMonitor* fnGetDpiForMonitor = reinterpret_cast<GetDpiForMonitor*>(GetProcAddress(hShcore, "GetDpiForMonitor"));
if (fnGetDpiForMonitor)
{
UINT uDpiX, uDpiY;
if (SUCCEEDED(fnGetDpiForMonitor(hMonitor, 0, &uDpiX, &uDpiY)) && uDpiX > 0 && uDpiY > 0)
{
*pnX = uDpiX;
*pnY = uDpiY;
bSetScaling = TRUE;
}
}
FreeLibrary(hShcore);
}
}
if (!bSetScaling)
{
HDC hdc = GetDC(NULL);
if (hdc)
{
*pnX = GetDeviceCaps(hdc, LOGPIXELSX);
*pnY = GetDeviceCaps(hdc, LOGPIXELSY);
ReleaseDC(NULL, hdc);
bSetScaling = TRUE;
}
}
if (!bSetScaling)
{
*pnX = DEFAULT_DPI;
*pnY = DEFAULT_DPI;
bSetScaling = TRUE;
}
return bSetScaling;
}
LPWSTR GetCurrentWorkingDirectory(HANDLE hProcess)
{
struct UPP {
long MaximumLength;
long Length;
long Flags;
long DebugFlags;
HANDLE ConsoleHandle;
long ConsoleFlags;
HANDLE StdInputHandle;
HANDLE StdOuputHandle;
HANDLE StdErrorHandle;
UNICODE_STRING CurrentDirectoryPath;
HANDLE CurrentDirectoryHandle;
UNICODE_STRING ImagePathName;
UNICODE_STRING CommandLine;
};
LPWSTR lpszReturn = 0;
HMODULE hModule = GetModuleHandleW(L"ntdll");
if (hModule) {
typedef NTSTATUS(__stdcall* fnNtQueryInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG);
fnNtQueryInformationProcess NtQueryInformationProcess = fnNtQueryInformationProcess(GetProcAddress(hModule, "NtQueryInformationProcess"));
if (NtQueryInformationProcess) {
PROCESS_BASIC_INFORMATION pbi = { 0 };
ULONG len = 0;
if (NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), &len) == 0 && len > 0) {
SIZE_T nRead = 0;
PEB peb = { 0 };
UPP upp = { 0 };
if (ReadProcessMemory(hProcess, pbi.PebBaseAddress, &peb, sizeof(peb), &nRead) && nRead > 0 &&
ReadProcessMemory(hProcess, peb.ProcessParameters, &upp, sizeof(upp), &nRead) && nRead > 0) {
PVOID buffer = upp.CurrentDirectoryPath.Buffer;
USHORT length = upp.CurrentDirectoryPath.Length;
lpszReturn = (LPWSTR)GlobalAlloc(0, (length / 2 + 1) * sizeof(WCHAR));
if (!ReadProcessMemory(hProcess, buffer, lpszReturn, length, &nRead) || nRead == 0)
{
GlobalFree(lpszReturn);
lpszReturn = 0;
}
lpszReturn[length / 2] = 0;
}
}
}
}
return lpszReturn;
}
LPWSTR RunCommand(LPCWSTR lpszCommand)
{
if (!lpszCommand) return 0;
LPWSTR lpszReturn = 0;
HANDLE readPipe;
HANDLE writePipe;
SECURITY_ATTRIBUTES sa = { 0 };
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
if (CreatePipe(&readPipe, &writePipe, &sa, 0) == 0) {
return 0;
}
STARTUPINFOW si = { 0 };
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.hStdOutput = writePipe;
si.hStdError = writePipe;
si.wShowWindow = SW_HIDE;
LPWSTR lpszSendBuffer = (LPWSTR)GlobalAlloc(0, (lstrlenW(lpszCommand) + 256) * sizeof(WCHAR));
if (lpszSendBuffer) {
WCHAR szCmdExePath[MAX_PATH] = { 0 };
GetEnvironmentVariableW(L"ComSpec", szCmdExePath, _countof(szCmdExePath));
lstrcpyW(lpszSendBuffer, szCmdExePath);
lstrcatW(lpszSendBuffer, L" /K ");
lstrcatW(lpszSendBuffer, lpszCommand);
PROCESS_INFORMATION pi = { 0 };
if (CreateProcessW(NULL, lpszSendBuffer, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
CHAR readBuf[1025];
std::string str;
BOOL end = FALSE;
do {
WaitForSingleObject(pi.hProcess, 1000);
DWORD totalLen, len;
if (PeekNamedPipe(readPipe, NULL, 0, NULL, &totalLen, NULL) && totalLen > 0) {
if (ReadFile(readPipe, readBuf, sizeof(readBuf) - 1, &len, NULL) && len > 0) {
readBuf[len] = 0;
str += readBuf;
}
}
else
{
end = TRUE;
}
} while (!end);
const int nLength = (int)str.length();
if (nLength) {
lpszReturn = (LPWSTR)GlobalAlloc(0, (nLength + 1) * sizeof(WCHAR));
MultiByteToWideChar(CP_THREAD_ACP, 0, str.c_str(), -1, lpszReturn, nLength + 1);
}
CloseHandle(pi.hThread);
{
LPWSTR lpszCurrentDirectory = GetCurrentWorkingDirectory(pi.hProcess);
SetCurrentDirectoryW(lpszCurrentDirectory);
GlobalFree((HGLOBAL)lpszCurrentDirectory);
}
TerminateProcess(pi.hProcess, 0);
CloseHandle(pi.hProcess);
}
GlobalFree(lpszSendBuffer);
}
CloseHandle(writePipe);
CloseHandle(readPipe);
return lpszReturn;
}
LPWSTR HtmlEncode(LPCWSTR lpText)
{
int i, m;
LPWSTR ptr;
const int n = lstrlenW(lpText);
for (i = 0, m = 0; i < n; i++)
{
switch (lpText[i])
{
case L'>':
case L'<':
m += 4;
break;
case L'&':
m += 5;
break;
default:
m++;
}
}
if (n == m)return 0;
LPWSTR lpOutText = (LPWSTR)GlobalAlloc(0, sizeof(WCHAR) * (m + 1));
for (i = 0, ptr = lpOutText; i <= n; i++)
{
switch (lpText[i])
{
case L'>':
lstrcpyW(ptr, L">");
ptr += lstrlenW(ptr);
break;
case L'<':
lstrcpyW(ptr, L"<");
ptr += lstrlenW(ptr);
break;
case L'&':
lstrcpyW(ptr, L"&");
ptr += lstrlenW(ptr);
break;
default:
*ptr++ = lpText[i];
}
}
return lpOutText;
}
DWORD WINAPI ThreadFunc(LPVOID p)
{
HWND hWnd = (HWND)p;
LPCWSTR lpszCommand = (LPCWSTR)GetWindowLongPtr(hWnd, DWLP_USER);
PostMessageW(hWnd, WM_APP, 0, (LPARAM)RunCommand(lpszCommand));
ExitThread(0);
}
VOID execBrowserCommand(IHTMLDocument2* pDocument, LPCWSTR lpszCommand)
{
VARIANT var = { 0 };
VARIANT_BOOL varBool = { 0 };
var.vt = VT_EMPTY;
BSTR command = SysAllocString(lpszCommand);
pDocument->execCommand(command, VARIANT_FALSE, var, &varBool);
SysFreeString(command);
}
VOID ScrollBottom(IHTMLDocument2* pDocument)
{
IHTMLWindow2* pHtmlWindow2;
pDocument->get_parentWindow(&pHtmlWindow2);
if (pHtmlWindow2) {
pHtmlWindow2->scrollTo(0, SHRT_MAX);
pHtmlWindow2->Release();
}
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static CComQIPtr<IWebBrowser2>pWB2;
static CComQIPtr<IHTMLDocument2>pDocument;
static HWND hEdit, hBrowser;
static HBRUSH hBrush;
static HFONT hFont;
static UINT uDpiX = DEFAULT_DPI, uDpiY = DEFAULT_DPI;
static HANDLE hThread;
static LPWSTR lpszCommand;
switch (msg)
{
case WM_CREATE:
hBrush = CreateSolidBrush(RGB(200, 219, 249));
hEdit = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", 0, WS_VISIBLE | WS_CHILD | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
SendMessageW(hEdit, EM_SETCUEBANNER, TRUE, (LPARAM)L"コマンドを入力");
hBrowser = CreateWindowExW(0, L"AtlAxWin140", L"about:blank", WS_CHILD | WS_VISIBLE | WS_VSCROLL, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
{
CComPtr<IUnknown> punkIE;
if (AtlAxGetControl(hBrowser, &punkIE) == S_OK) {
pWB2 = punkIE;
punkIE.Release();
if (pWB2) {
pWB2->put_Silent(VARIANT_TRUE);
pWB2->put_RegisterAsDropTarget(VARIANT_FALSE);
pWB2->get_Document((IDispatch**)&pDocument);
{
CComPtr<IUnknown> punkIE;
ATL::CComPtr<IAxWinAmbientDispatch> ambient;
AtlAxGetHost(hBrowser, &punkIE);
ambient = punkIE;
if (ambient) {
ambient->put_AllowContextMenu(VARIANT_FALSE);
}
}
}
}
}
if (!pDocument) {
return -1;
}
{
WCHAR szModuleFilePath[MAX_PATH] = { 0 };
GetModuleFileNameW(NULL, szModuleFilePath, MAX_PATH);
WCHAR szURL[MAX_PATH] = { 0 };
wsprintfW(szURL, L"res://%s/%d", szModuleFilePath, IDR_HTML1);
BSTR url = SysAllocString(szURL);
pWB2->Navigate(url, NULL, NULL, NULL, NULL);
SysFreeString(url);
}
SendMessage(hWnd, WM_APP + 1, 0, 0);
RECT rect;
GetWindowRect(hWnd, &rect);
SetWindowPos(hWnd, NULL, 0, 0, (rect.right - rect.left) / 3, (rect.bottom - rect.top) / 2, SWP_NOMOVE | SWP_NOZORDER | SWP_NOSENDCHANGING | SWP_NOREDRAW);
break;
case WM_SIZE:
MoveWindow(hBrowser, 0, 0, LOWORD(lParam), HIWORD(lParam) - POINT2PIXEL(32), TRUE);
MoveWindow(hEdit, 0, HIWORD(lParam) - POINT2PIXEL(32), LOWORD(lParam), POINT2PIXEL(32), TRUE);
break;
case WM_CTLCOLOREDIT:
case WM_CTLCOLORSTATIC:
SetBkMode((HDC)wParam, TRANSPARENT);
return(INT_PTR)hBrush;
case WM_SETFOCUS:
SetFocus(hEdit);
break;
case WM_APP:
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
hThread = 0;
{
LPCWSTR lpszReturnString = (LPWSTR)lParam;
if (lpszReturnString) {
LPWSTR lpszReturnString2 = HtmlEncode(lpszReturnString);
if (lpszReturnString2) {
GlobalFree((HGLOBAL)lpszReturnString);
lpszReturnString = lpszReturnString2;
}
const int nHtmlLength = lstrlenW(lpszReturnString) + 256;
LPWSTR lpszHtml = (LPWSTR)GlobalAlloc(0, nHtmlLength * sizeof(WCHAR));
lstrcpyW(lpszHtml, L"<div class=\"result\"><div class=\"icon\"><img></div><div class=\"chatting\"><div class=\"output\"><pre>");
lstrcatW(lpszHtml, lpszReturnString);
GlobalFree((HGLOBAL)lpszReturnString);
lstrcatW(lpszHtml, L"</pre></div></div></div>");
CComQIPtr<IHTMLElement>pElementBody;
pDocument->get_body((IHTMLElement**)&pElementBody);
if (pElementBody) {
BSTR where = SysAllocString(L"beforeEnd");
BSTR html = SysAllocString(lpszHtml);
pElementBody->insertAdjacentHTML(where, html);
SysFreeString(where);
SysFreeString(html);
pElementBody.Release();
ScrollBottom(pDocument);
}
GlobalFree(lpszHtml);
}
}
EnableWindow(hBrowser, TRUE);
EnableWindow(hEdit, TRUE);
SetFocus(hEdit);
break;
case WM_COMMAND:
if (LOWORD(wParam) == ID_RUN)
{
if (GetFocus() != hEdit)
SetFocus(hEdit);
const int nTextLength = GetWindowTextLength(hEdit);
if (nTextLength > 0) {
GlobalFree(lpszCommand);
lpszCommand = (LPWSTR)GlobalAlloc(0, (nTextLength + 1) * sizeof(WCHAR));
if (lpszCommand) {
GetWindowTextW(hEdit, lpszCommand, nTextLength + 1);
SetWindowLongPtrW(hWnd, DWLP_USER, (LONG_PTR)lpszCommand);
LPWSTR lpszCommand2 = HtmlEncode(lpszCommand);
UINT nHtmlLength = (lpszCommand2 ? lstrlenW(lpszCommand2) : nTextLength) + 256;
LPWSTR lpszHtml = (LPWSTR)GlobalAlloc(0, nHtmlLength * sizeof(WCHAR));
if (lpszHtml) {
lstrcpyW(lpszHtml, L"<div class=\"input\"><pre>");
lstrcatW(lpszHtml, lpszCommand2 ? lpszCommand2 : lpszCommand);
lstrcatW(lpszHtml, L"</pre></div>");
CComQIPtr<IHTMLElement>pElementBody;
pDocument->get_body((IHTMLElement**)&pElementBody);
if (pElementBody) {
BSTR where = SysAllocString(L"beforeEnd");
BSTR html = SysAllocString(lpszHtml);
pElementBody->insertAdjacentHTML(where, html);
SysFreeString(where);
SysFreeString(html);
pElementBody.Release();
ScrollBottom(pDocument);
}
GlobalFree(lpszHtml);
SetWindowText(hEdit, 0);
DWORD dwParam;
EnableWindow(hBrowser, FALSE);
EnableWindow(hEdit, FALSE);
hThread = CreateThread(0, 0, ThreadFunc, (LPVOID)hWnd, 0, &dwParam);
}
GlobalFree((HGLOBAL)lpszCommand2);
}
}
}
else if (LOWORD(wParam) == ID_COPY) {
if (GetFocus() == hEdit) {
SendMessage(hEdit, WM_COPY, 0, 0);
} else {
execBrowserCommand(pDocument, L"Copy");
execBrowserCommand(pDocument, L"Unselect");
SetFocus(hEdit);
}
}
else if (LOWORD(wParam) == ID_TAB) {
execBrowserCommand(pDocument, L"Unselect");
SendMessage(hEdit, EM_SETSEL, 0, -1);
SetFocus(hEdit);
}
break;
case WM_NCCREATE:
{
const HMODULE hModUser32 = GetModuleHandleW(L"user32.dll");
if (hModUser32)
{
typedef BOOL(WINAPI* fnTypeEnableNCScaling)(HWND);
const fnTypeEnableNCScaling fnEnableNCScaling = (fnTypeEnableNCScaling)GetProcAddress(hModUser32, "EnableNonClientDpiScaling");
if (fnEnableNCScaling)
{
fnEnableNCScaling(hWnd);
}
}
}
return DefWindowProc(hWnd, msg, wParam, lParam);
case WM_DPICHANGED:
case WM_APP+1:
GetScaling(hWnd, &uDpiX, &uDpiY);
DeleteObject(hFont);
hFont = CreateFontW(-POINT2PIXEL(12), 0, 0, 0, FW_NORMAL, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, L"Consolas");
SendMessage(hEdit, WM_SETFONT, (WPARAM)hFont, 0);
break;
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_DESTROY:
GlobalFree(lpszCommand);
pDocument.Release();
pWB2.Release();
DeleteObject(hBrush);
DeleteObject(hFont);
PostQuitMessage(0);
break;
default:
return DefDlgProc(hWnd, msg, wParam, lParam);
}
return 0;
}
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
if (FAILED(CoInitialize(NULL)))
{
return 0;
}
::AtlAxWinInit();
MSG msg = { 0 };
{
CComModule _Module;
WNDCLASS wndclass = {
0,
WndProc,
0,
DLGWINDOWEXTRA,
hInstance,
LoadIcon(hInstance,(LPCTSTR)IDI_ICON1),
0,
0,
0,
szClassName
};
RegisterClass(&wndclass);
HWND hWnd = CreateWindow(
szClassName,
TEXT("コマンド プロンプト (チャット風)"),
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
CW_USEDEFAULT,
0,
CW_USEDEFAULT,
0,
0,
0,
hInstance,
0
);
ShowWindow(hWnd, SW_SHOWDEFAULT);
UpdateWindow(hWnd);
HACCEL hAccel = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1));
while (GetMessage(&msg, 0, 0, 0))
{
if (!TranslateAccelerator(hWnd, hAccel, &msg) && !IsDialogMessage(hWnd, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
::AtlAxWinTerm();
CoUninitialize();
return (int)msg.wParam;
}