1
0

Main.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. //---------------------------------------------------------------------------
  2. #include <stdexcept>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <windows.h>
  6. #include "Console.h"
  7. #define MAX_ATTEMPTS 10
  8. //---------------------------------------------------------------------------
  9. #define LENOF(x) ( (sizeof((x))) / (sizeof(*(x))))
  10. //---------------------------------------------------------------------------
  11. using namespace std;
  12. HANDLE ConsoleInput = NULL;
  13. HANDLE ConsoleOutput = NULL;
  14. HANDLE Child = NULL;
  15. HANDLE CancelEvent = NULL;
  16. HANDLE InputTimerEvent = NULL;
  17. unsigned int OutputType = FILE_TYPE_UNKNOWN;
  18. unsigned int InputType = FILE_TYPE_UNKNOWN;
  19. enum { RESULT_GLOBAL_ERROR = 1, RESULT_INIT_ERROR = 2, RESULT_PROCESSING_ERROR = 3,
  20. RESULT_UNKNOWN_ERROR = 4 };
  21. const wchar_t* CONSOLE_CHILD_PARAM = L"consolechild";
  22. //---------------------------------------------------------------------------
  23. inline TConsoleCommStruct* GetCommStruct(HANDLE FileMapping)
  24. {
  25. TConsoleCommStruct* Result;
  26. Result = static_cast<TConsoleCommStruct*>(MapViewOfFile(FileMapping,
  27. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  28. if (Result == NULL)
  29. {
  30. throw runtime_error("Cannot open mapping object.");
  31. }
  32. return Result;
  33. }
  34. //---------------------------------------------------------------------------
  35. inline void FreeCommStruct(TConsoleCommStruct* CommStruct)
  36. {
  37. UnmapViewOfFile(CommStruct);
  38. }
  39. //---------------------------------------------------------------------------
  40. void InitializeConsole(wchar_t* InstanceName, HANDLE& RequestEvent, HANDLE& ResponseEvent,
  41. HANDLE& CancelEvent, HANDLE& FileMapping, HANDLE& Job)
  42. {
  43. unsigned int Process = GetCurrentProcessId();
  44. int Attempts = 0;
  45. wchar_t Name[MAX_PATH];
  46. bool UniqEvent;
  47. do
  48. {
  49. if (Attempts > MAX_ATTEMPTS)
  50. {
  51. throw runtime_error("Cannot find unique name for event object.");
  52. }
  53. int InstanceNumber;
  54. #ifdef CONSOLE_TEST
  55. InstanceNumber = 1;
  56. #else
  57. InstanceNumber = random(1000);
  58. #endif
  59. swprintf(InstanceName, L"_%u_%d", Process, InstanceNumber);
  60. swprintf(Name, L"%s%s", CONSOLE_EVENT_REQUEST, InstanceName);
  61. HANDLE EventHandle = OpenEvent(EVENT_ALL_ACCESS, false, Name);
  62. UniqEvent = (EventHandle == NULL);
  63. if (!UniqEvent)
  64. {
  65. CloseHandle(EventHandle);
  66. }
  67. Attempts++;
  68. }
  69. while (!UniqEvent);
  70. RequestEvent = CreateEvent(NULL, false, false, Name);
  71. if (RequestEvent == NULL)
  72. {
  73. throw runtime_error("Cannot create request event object.");
  74. }
  75. swprintf(Name, L"%s%s", CONSOLE_EVENT_RESPONSE, InstanceName);
  76. ResponseEvent = CreateEvent(NULL, false, false, Name);
  77. if (ResponseEvent == NULL)
  78. {
  79. throw runtime_error("Cannot create response event object.");
  80. }
  81. swprintf(Name, L"%s%s", CONSOLE_EVENT_CANCEL, InstanceName);
  82. CancelEvent = CreateEvent(NULL, false, false, Name);
  83. if (CancelEvent == NULL)
  84. {
  85. throw runtime_error("Cannot create cancel event object.");
  86. }
  87. swprintf(Name, L"%s%s", CONSOLE_MAPPING, InstanceName);
  88. FileMapping = CreateFileMapping((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  89. 0, sizeof(TConsoleCommStruct), Name);
  90. if (FileMapping == NULL)
  91. {
  92. throw runtime_error("Cannot create mapping object.");
  93. }
  94. swprintf(Name, L"%s%s", CONSOLE_JOB, InstanceName);
  95. Job = CreateJobObject(NULL, Name);
  96. if (Job == NULL)
  97. {
  98. throw runtime_error("Cannot create job object.");
  99. }
  100. JOBOBJECT_EXTENDED_LIMIT_INFORMATION ExtendedLimitInformation;
  101. memset(&ExtendedLimitInformation, 0, sizeof(ExtendedLimitInformation));
  102. ExtendedLimitInformation.BasicLimitInformation.LimitFlags =
  103. JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
  104. if (SetInformationJobObject(Job, JobObjectExtendedLimitInformation,
  105. &ExtendedLimitInformation, sizeof(ExtendedLimitInformation)) == 0)
  106. {
  107. CloseHandle(Job);
  108. Job = NULL;
  109. }
  110. TConsoleCommStruct* CommStruct = GetCommStruct(FileMapping);
  111. CommStruct->Size = sizeof(TConsoleCommStruct);
  112. CommStruct->Version = TConsoleCommStruct::CurrentVersion;
  113. CommStruct->Event = TConsoleCommStruct::NONE;
  114. FreeCommStruct(CommStruct);
  115. }
  116. //---------------------------------------------------------------------------
  117. // duplicated in Common.cpp
  118. bool __fastcall CutToken(const wchar_t*& Str, wchar_t* Token)
  119. {
  120. bool Result;
  121. // inspired by Putty's sftp_getcmd() from PSFTP.C
  122. int Length = wcslen(Str);
  123. int Index = 0;
  124. while ((Index < Length) &&
  125. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  126. {
  127. Index++;
  128. }
  129. if (Index < Length)
  130. {
  131. bool Quoting = false;
  132. while (Index < Length)
  133. {
  134. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  135. {
  136. break;
  137. }
  138. else if ((Str[Index] == L'"') && (Index + 1 < Length) &&
  139. (Str[Index + 1] == L'"'))
  140. {
  141. Index += 2;
  142. *Token = L'"';
  143. Token++;
  144. }
  145. else if (Str[Index] == L'"')
  146. {
  147. Index++;
  148. Quoting = !Quoting;
  149. }
  150. else
  151. {
  152. *Token = Str[Index];
  153. Token++;
  154. Index++;
  155. }
  156. }
  157. if (Index < Length)
  158. {
  159. Index++;
  160. }
  161. Str += Index;
  162. Result = true;
  163. }
  164. else
  165. {
  166. Result = false;
  167. Str += Length;
  168. }
  169. *Token = L'\0';
  170. return Result;
  171. }
  172. //---------------------------------------------------------------------------
  173. void GetProductVersion(wchar_t* ProductVersion)
  174. {
  175. wchar_t Buffer[MAX_PATH];
  176. DWORD ModuleNameLen = GetModuleFileName(NULL, Buffer, MAX_PATH);
  177. if ((ModuleNameLen == 0) || (ModuleNameLen == MAX_PATH))
  178. {
  179. throw runtime_error("Error retrieving executable name.");
  180. }
  181. ProductVersion[0] = '\0';
  182. unsigned long Handle;
  183. unsigned int Size = GetFileVersionInfoSize(Buffer, &Handle);
  184. if (Size > 0)
  185. {
  186. void * VersionInfo = new char[Size];
  187. VS_FIXEDFILEINFO* FixedFileInfo;
  188. unsigned int Length;
  189. if (GetFileVersionInfo(Buffer, Handle, Size, VersionInfo))
  190. {
  191. if (VerQueryValue(VersionInfo, L"\\", (void**)&FixedFileInfo, &Length))
  192. {
  193. int ProductMajor = HIWORD(FixedFileInfo->dwProductVersionMS);
  194. int ProductMinor = LOWORD(FixedFileInfo->dwProductVersionMS);
  195. int ProductBuild = HIWORD(FixedFileInfo->dwProductVersionLS);
  196. if ((ProductMajor >= 0) && (ProductMajor <= 9) &&
  197. (ProductMinor >= 0) && (ProductMinor <= 9) &&
  198. (ProductBuild >= 0) && (ProductBuild <= 9))
  199. {
  200. ProductVersion[0] = static_cast<wchar_t>(L'0' + ProductMajor);
  201. ProductVersion[1] = static_cast<wchar_t>(L'0' + ProductMinor);
  202. ProductVersion[2] = static_cast<wchar_t>(L'0' + ProductBuild);
  203. ProductVersion[3] = L'\0';
  204. }
  205. }
  206. }
  207. delete[] VersionInfo;
  208. }
  209. if (ProductVersion[0] == L'\0')
  210. {
  211. throw runtime_error("Error retrieving product version.");
  212. }
  213. }
  214. //---------------------------------------------------------------------------
  215. void InitializeChild(const wchar_t* CommandLine, const wchar_t* InstanceName, HANDLE& Child)
  216. {
  217. int SkipParam = 0;
  218. wchar_t ChildPath[MAX_PATH] = L"";
  219. size_t CommandLineLen = wcslen(CommandLine);
  220. wchar_t* Buffer = new wchar_t[(CommandLineLen > MAX_PATH ? CommandLineLen : MAX_PATH) + 1];
  221. int Count = 0;
  222. const wchar_t* P = CommandLine;
  223. while (CutToken(P, Buffer))
  224. {
  225. if ((wcschr(L"-/", Buffer[0]) != NULL) &&
  226. (wcsncmpi(Buffer + 1, CONSOLE_CHILD_PARAM, wcslen(CONSOLE_CHILD_PARAM)) == 0) &&
  227. (Buffer[wcslen(CONSOLE_CHILD_PARAM) + 1] == L'='))
  228. {
  229. SkipParam = Count;
  230. wcscpy(ChildPath, Buffer + 1 + wcslen(CONSOLE_CHILD_PARAM) + 1);
  231. }
  232. ++Count;
  233. }
  234. if (wcslen(ChildPath) == 0)
  235. {
  236. DWORD ModuleNameLen = GetModuleFileName(NULL, Buffer, MAX_PATH);
  237. if ((ModuleNameLen == 0) || (ModuleNameLen == MAX_PATH))
  238. {
  239. throw runtime_error("Error retrieving executable name.");
  240. }
  241. const wchar_t* LastDelimiter = wcsrchr(Buffer, L'\\');
  242. const wchar_t* AppFileName;
  243. if (LastDelimiter != NULL)
  244. {
  245. wcsncpy(ChildPath, Buffer, LastDelimiter - Buffer + 1);
  246. ChildPath[LastDelimiter - Buffer + 1] = L'\0';
  247. AppFileName = LastDelimiter + 1;
  248. }
  249. else
  250. {
  251. ChildPath[0] = L'\0';
  252. AppFileName = Buffer;
  253. }
  254. const wchar_t* ExtensionStart = wcsrchr(AppFileName, L'.');
  255. if (ExtensionStart != NULL)
  256. {
  257. wchar_t* End = ChildPath + wcslen(ChildPath);
  258. wcsncpy(End, AppFileName, ExtensionStart - AppFileName);
  259. *(End + (ExtensionStart - AppFileName)) = L'\0';
  260. }
  261. else
  262. {
  263. wcscat(ChildPath, AppFileName);
  264. }
  265. wcscat(ChildPath, L".exe");
  266. }
  267. wchar_t ProductVersion[4];
  268. GetProductVersion(ProductVersion);
  269. wchar_t* Parameters = new wchar_t[(CommandLineLen * 2) + 100 + (Count * 3) + 1];
  270. wsprintf(Parameters, L"\"%s\" /console=%s /consoleinstance=%s ", ChildPath, ProductVersion, InstanceName);
  271. P = CommandLine;
  272. // skip executable path
  273. CutToken(P, Buffer);
  274. int i = 1;
  275. while (CutToken(P, Buffer))
  276. {
  277. if (i != SkipParam)
  278. {
  279. wcscat(Parameters, L"\"");
  280. wchar_t* P2 = Parameters + wcslen(Parameters);
  281. const wchar_t* P3 = Buffer;
  282. const wchar_t* BufferEnd = Buffer + wcslen(Buffer) + 1;
  283. while (P3 != BufferEnd)
  284. {
  285. *P2 = *P3;
  286. ++P2;
  287. if (*P3 == L'"')
  288. {
  289. *P2 = L'"';
  290. ++P2;
  291. }
  292. ++P3;
  293. }
  294. wcscat(Parameters, L"\" ");
  295. }
  296. ++i;
  297. }
  298. delete[] Buffer;
  299. STARTUPINFO StartupInfo = { sizeof(STARTUPINFO) };
  300. PROCESS_INFORMATION ProcessInfomation;
  301. BOOL Result =
  302. CreateProcess(ChildPath, Parameters, NULL, NULL, false, 0, NULL, NULL,
  303. &StartupInfo, &ProcessInfomation);
  304. delete[] Parameters;
  305. if (Result)
  306. {
  307. Child = ProcessInfomation.hProcess;
  308. }
  309. else
  310. {
  311. throw runtime_error("Cannot start WinSCP application.");
  312. }
  313. }
  314. //---------------------------------------------------------------------------
  315. void FinalizeChild(HANDLE Child)
  316. {
  317. if (Child != NULL)
  318. {
  319. TerminateProcess(Child, 0);
  320. CloseHandle(Child);
  321. }
  322. }
  323. //---------------------------------------------------------------------------
  324. void FinalizeConsole(const wchar_t* /*InstanceName*/, HANDLE RequestEvent,
  325. HANDLE ResponseEvent, HANDLE CancelEvent, HANDLE FileMapping, HANDLE Job)
  326. {
  327. CloseHandle(RequestEvent);
  328. CloseHandle(ResponseEvent);
  329. CloseHandle(CancelEvent);
  330. CloseHandle(FileMapping);
  331. if (Job != NULL)
  332. {
  333. CloseHandle(Job);
  334. }
  335. }
  336. //---------------------------------------------------------------------------
  337. static wchar_t LastFromBeginning[sizeof(TConsoleCommStruct::TPrintEvent)] = L""; //???
  338. //---------------------------------------------------------------------------
  339. inline void Flush()
  340. {
  341. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE))
  342. {
  343. fflush(stdout);
  344. }
  345. }
  346. //---------------------------------------------------------------------------
  347. void Print(const wchar_t* Message)
  348. {
  349. int Size = WideCharToMultiByte(CP_UTF8, 0, Message, -1, 0, 0, 0, 0);
  350. if (Size > 0)
  351. {
  352. char* Buffer = new char[(Size * 2) + 1];
  353. if (WideCharToMultiByte(CP_UTF8, 0, Message, -1, Buffer, Size, 0, 0) > 0)
  354. {
  355. Buffer[Size] = '\0';
  356. char* Ptr = Buffer;
  357. while ((Ptr = strchr(Ptr, '\n')) != NULL)
  358. {
  359. memmove(Ptr + 1, Ptr, strlen(Ptr) + 1);
  360. *Ptr = '\r';
  361. Ptr += 2;
  362. }
  363. unsigned long Written;
  364. WriteFile(ConsoleOutput, Buffer, strlen(Buffer), &Written, NULL);
  365. }
  366. delete[] Buffer;
  367. }
  368. }
  369. //---------------------------------------------------------------------------
  370. void Print(bool FromBeginning, const wchar_t* Message)
  371. {
  372. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE))
  373. {
  374. if (FromBeginning && (Message[0] != L'\n'))
  375. {
  376. wcscpy(LastFromBeginning, Message);
  377. }
  378. else
  379. {
  380. if (LastFromBeginning[0] != L'\0')
  381. {
  382. Print(LastFromBeginning);
  383. LastFromBeginning[0] = L'\0';
  384. }
  385. if (FromBeginning && (Message[0] == L'\n'))
  386. {
  387. Print(L"\n");
  388. wcscpy(LastFromBeginning, Message + 1);
  389. }
  390. else
  391. {
  392. Print(Message);
  393. }
  394. Flush();
  395. }
  396. }
  397. else
  398. {
  399. unsigned long Written;
  400. if (FromBeginning)
  401. {
  402. WriteConsole(ConsoleOutput, L"\r", 1, &Written, NULL);
  403. }
  404. WriteConsole(ConsoleOutput, Message, wcslen(Message), &Written, NULL);
  405. }
  406. }
  407. //---------------------------------------------------------------------------
  408. inline void ProcessPrintEvent(TConsoleCommStruct::TPrintEvent& Event)
  409. {
  410. Print(Event.FromBeginning, Event.Message);
  411. }
  412. //---------------------------------------------------------------------------
  413. void CancelInput()
  414. {
  415. SetEvent(CancelEvent);
  416. }
  417. //---------------------------------------------------------------------------
  418. void BreakInput()
  419. {
  420. FlushConsoleInputBuffer(ConsoleInput);
  421. INPUT_RECORD InputRecord;
  422. memset(&InputRecord, 0, sizeof(InputRecord));
  423. InputRecord.EventType = KEY_EVENT;
  424. InputRecord.Event.KeyEvent.bKeyDown = true;
  425. InputRecord.Event.KeyEvent.wRepeatCount = 1;
  426. InputRecord.Event.KeyEvent.uChar.UnicodeChar = L'\r';
  427. unsigned long Written;
  428. WriteConsoleInput(ConsoleInput, &InputRecord, 1, &Written);
  429. CancelInput();
  430. }
  431. //---------------------------------------------------------------------------
  432. DWORD WINAPI InputTimerThreadProc(void* Parameter)
  433. {
  434. unsigned int Timer = reinterpret_cast<unsigned int>(Parameter);
  435. if (WaitForSingleObject(InputTimerEvent, Timer) == WAIT_TIMEOUT)
  436. {
  437. BreakInput();
  438. }
  439. return 0;
  440. }
  441. //---------------------------------------------------------------------------
  442. void ProcessInputEvent(TConsoleCommStruct::TInputEvent& Event)
  443. {
  444. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE))
  445. {
  446. unsigned long Bytes = 0;
  447. unsigned long Read;
  448. bool Result;
  449. char Ch;
  450. char Buf[LENOF(Event.Str) * 3];
  451. while (((Result = (ReadFile(ConsoleInput, &Ch, 1, &Read, NULL) != 0)) != false) &&
  452. (Read > 0) && (Bytes < LENOF(Buf) - 1) && (Ch != '\n'))
  453. {
  454. if (Ch != '\r')
  455. {
  456. Buf[Bytes] = Ch;
  457. Bytes++;
  458. }
  459. }
  460. Buf[Bytes] = L'\0';
  461. MultiByteToWideChar(CP_UTF8, 0, Buf, -1, Event.Str, LENOF(Event.Str) - 1);
  462. Event.Str[LENOF(Event.Str) - 1] = L'\0';
  463. Print(false, Event.Str);
  464. Print(false, L"\n");
  465. Event.Result = ((Result && (Read > 0)) || (Bytes > 0));
  466. }
  467. else
  468. {
  469. unsigned long PrevMode, NewMode;
  470. GetConsoleMode(ConsoleInput, &PrevMode);
  471. NewMode = PrevMode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
  472. if (Event.Echo)
  473. {
  474. NewMode |= ENABLE_ECHO_INPUT;
  475. }
  476. else
  477. {
  478. NewMode &= ~ENABLE_ECHO_INPUT;
  479. }
  480. SetConsoleMode(ConsoleInput, NewMode);
  481. HANDLE InputTimerThread = NULL;
  482. try
  483. {
  484. if (Event.Timer > 0)
  485. {
  486. unsigned long ThreadId;
  487. InputTimerEvent = CreateEvent(NULL, false, false, NULL);
  488. InputTimerThread = CreateThread(NULL, 0, InputTimerThreadProc,
  489. reinterpret_cast<void *>(Event.Timer), 0, &ThreadId);
  490. }
  491. unsigned long Read;
  492. Event.Result = ReadConsole(ConsoleInput, Event.Str, LENOF(Event.Str) - 1, &Read, NULL);
  493. Event.Str[Read] = L'\0';
  494. bool PendingCancel = (WaitForSingleObject(CancelEvent, 0) == WAIT_OBJECT_0);
  495. if (PendingCancel || !Event.Echo)
  496. {
  497. WriteFile(ConsoleOutput, "\n", 1, NULL, NULL);
  498. Flush();
  499. }
  500. if (PendingCancel || (Read == 0))
  501. {
  502. Event.Result = false;
  503. }
  504. }
  505. __finally
  506. {
  507. if (InputTimerThread != NULL)
  508. {
  509. SetEvent(InputTimerEvent);
  510. WaitForSingleObject(InputTimerThread, 100);
  511. CloseHandle(InputTimerEvent);
  512. InputTimerEvent = NULL;
  513. CloseHandle(InputTimerThread);
  514. }
  515. SetConsoleMode(ConsoleInput, PrevMode);
  516. }
  517. }
  518. }
  519. //---------------------------------------------------------------------------
  520. void ProcessChoiceEvent(TConsoleCommStruct::TChoiceEvent& Event)
  521. {
  522. // note that if output is redirected to file, input is still FILE_TYPE_CHAR
  523. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE))
  524. {
  525. if (Event.Timeouting)
  526. {
  527. Sleep(Event.Timer);
  528. Event.Result = Event.Timeouted;
  529. }
  530. else
  531. {
  532. Event.Result = Event.Break;
  533. }
  534. }
  535. else
  536. {
  537. Event.Result = 0;
  538. unsigned long PrevMode, NewMode;
  539. GetConsoleMode(ConsoleInput, &PrevMode);
  540. NewMode = (PrevMode | ENABLE_PROCESSED_INPUT) & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  541. SetConsoleMode(ConsoleInput, NewMode);
  542. unsigned int ATimer = Event.Timer;
  543. try
  544. {
  545. do
  546. {
  547. unsigned long Read;
  548. INPUT_RECORD Record;
  549. if ((PeekConsoleInput(ConsoleInput, &Record, 1, &Read) != 0) &&
  550. (Read == 1))
  551. {
  552. if ((ReadConsoleInput(ConsoleInput, &Record, 1, &Read) != 0) &&
  553. (Read == 1))
  554. {
  555. bool PendingCancel = (WaitForSingleObject(CancelEvent, 0) == WAIT_OBJECT_0);
  556. if (PendingCancel)
  557. {
  558. Event.Result = Event.Break;
  559. }
  560. else if ((Record.EventType == KEY_EVENT) &&
  561. Record.Event.KeyEvent.bKeyDown)
  562. {
  563. // This happens when Shift key is pressed
  564. if (Record.Event.KeyEvent.uChar.AsciiChar != 0)
  565. {
  566. wchar_t CStr[2];
  567. CStr[0] = Record.Event.KeyEvent.uChar.AsciiChar;
  568. CStr[1] = L'\0';
  569. CharUpperBuff(CStr, 1);
  570. wchar_t C = CStr[0];
  571. if (C == 27)
  572. {
  573. Event.Result = Event.Cancel;
  574. }
  575. else if ((wcschr(Event.Options, C) != NULL) &&
  576. ((Record.Event.KeyEvent.dwControlKeyState &
  577. (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED | LEFT_ALT_PRESSED |
  578. RIGHT_ALT_PRESSED)) == 0))
  579. {
  580. Event.Result = wcschr(Event.Options, C) - Event.Options + 1;
  581. }
  582. }
  583. }
  584. }
  585. }
  586. if (Event.Result == 0)
  587. {
  588. unsigned int TimerSlice = 50;
  589. Sleep(TimerSlice);
  590. if (Event.Timer > 0)
  591. {
  592. if (ATimer > TimerSlice)
  593. {
  594. ATimer -= TimerSlice;
  595. }
  596. else
  597. {
  598. Event.Result = Event.Timeouted;
  599. }
  600. }
  601. }
  602. }
  603. while (Event.Result == 0);
  604. SetConsoleMode(ConsoleInput, PrevMode);
  605. }
  606. catch(...)
  607. {
  608. SetConsoleMode(ConsoleInput, PrevMode);
  609. throw;
  610. }
  611. }
  612. }
  613. //---------------------------------------------------------------------------
  614. inline void ProcessTitleEvent(TConsoleCommStruct::TTitleEvent& Event)
  615. {
  616. SetConsoleTitle(Event.Title);
  617. }
  618. //---------------------------------------------------------------------------
  619. inline void ProcessInitEvent(TConsoleCommStruct::TInitEvent& Event)
  620. {
  621. Event.InputType = InputType;
  622. Event.OutputType = OutputType;
  623. // default anyway
  624. Event.WantsProgress = false;
  625. }
  626. //---------------------------------------------------------------------------
  627. void ProcessEvent(HANDLE ResponseEvent, HANDLE FileMapping)
  628. {
  629. TConsoleCommStruct* CommStruct = GetCommStruct(FileMapping);
  630. try
  631. {
  632. if (CommStruct->Version != TConsoleCommStruct::CurrentVersionConfirmed)
  633. {
  634. throw runtime_error("Incompatible console protocol version");
  635. }
  636. switch (CommStruct->Event)
  637. {
  638. case TConsoleCommStruct::PRINT:
  639. ProcessPrintEvent(CommStruct->PrintEvent);
  640. break;
  641. case TConsoleCommStruct::INPUT:
  642. ProcessInputEvent(CommStruct->InputEvent);
  643. break;
  644. case TConsoleCommStruct::CHOICE:
  645. ProcessChoiceEvent(CommStruct->ChoiceEvent);
  646. break;
  647. case TConsoleCommStruct::TITLE:
  648. ProcessTitleEvent(CommStruct->TitleEvent);
  649. break;
  650. case TConsoleCommStruct::INIT:
  651. ProcessInitEvent(CommStruct->InitEvent);
  652. break;
  653. default:
  654. throw runtime_error("Unknown event");
  655. }
  656. FreeCommStruct(CommStruct);
  657. SetEvent(ResponseEvent);
  658. }
  659. catch(...)
  660. {
  661. FreeCommStruct(CommStruct);
  662. throw;
  663. }
  664. }
  665. //---------------------------------------------------------------------------
  666. BOOL WINAPI HandlerRoutine(DWORD CtrlType)
  667. {
  668. if ((CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_BREAK_EVENT))
  669. {
  670. CancelInput();
  671. return true;
  672. }
  673. else
  674. {
  675. FinalizeChild(Child);
  676. return false;
  677. }
  678. }
  679. //---------------------------------------------------------------------------
  680. #pragma argsused
  681. int wmain(int /*argc*/, wchar_t* /*argv*/[])
  682. {
  683. unsigned long Result = RESULT_UNKNOWN_ERROR;
  684. try
  685. {
  686. randomize();
  687. OSVERSIONINFO VersionInfo;
  688. VersionInfo.dwOSVersionInfoSize = sizeof(VersionInfo);
  689. GetVersionEx(&VersionInfo);
  690. ConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
  691. InputType = GetFileType(ConsoleInput);
  692. SetConsoleCtrlHandler(HandlerRoutine, true);
  693. unsigned int SavedConsoleCP = GetConsoleCP();
  694. unsigned int SavedConsoleOutputCP = GetConsoleOutputCP();
  695. ConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  696. OutputType = GetFileType(ConsoleOutput);
  697. bool SupportsUtf8ConsoleOutput =
  698. ((VersionInfo.dwMajorVersion == 6) && (VersionInfo.dwMinorVersion >= 1)) ||
  699. (VersionInfo.dwMajorVersion > 6);
  700. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE) ||
  701. SupportsUtf8ConsoleOutput)
  702. {
  703. SetConsoleCP(CP_UTF8);
  704. }
  705. else
  706. {
  707. SetConsoleCP(CP_ACP);
  708. }
  709. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE) ||
  710. SupportsUtf8ConsoleOutput)
  711. {
  712. SetConsoleOutputCP(CP_UTF8);
  713. }
  714. else
  715. {
  716. SetConsoleOutputCP(CP_ACP);
  717. }
  718. wchar_t InstanceName[MAX_PATH];
  719. HANDLE RequestEvent, ResponseEvent, FileMapping, Job;
  720. InitializeConsole(InstanceName, RequestEvent, ResponseEvent,
  721. CancelEvent, FileMapping, Job);
  722. wchar_t SavedTitle[512];
  723. GetConsoleTitle(SavedTitle, LENOF(SavedTitle));
  724. try
  725. {
  726. #ifndef CONSOLE_TEST
  727. InitializeChild(GetCommandLine(), InstanceName, Child);
  728. #endif
  729. try
  730. {
  731. bool Continue = true;
  732. do
  733. {
  734. HANDLE Handles[2];
  735. Handles[0] = RequestEvent;
  736. Handles[1] = Child;
  737. unsigned int HandleCount;
  738. #ifndef CONSOLE_TEST
  739. HandleCount = 2;
  740. #else
  741. HandleCount = 1;
  742. #endif
  743. unsigned long WaitResult =
  744. WaitForMultipleObjects(HandleCount, Handles, false, INFINITE);
  745. switch (WaitResult)
  746. {
  747. case WAIT_OBJECT_0:
  748. ProcessEvent(ResponseEvent, FileMapping);
  749. break;
  750. case WAIT_OBJECT_0 + 1:
  751. GetExitCodeProcess(Child, &Result);
  752. CloseHandle(Child);
  753. Child = NULL;
  754. Continue = false;
  755. break;
  756. default:
  757. throw runtime_error("Error waiting for communication from child process.");
  758. }
  759. }
  760. while (Continue);
  761. // flush pending progress message
  762. Print(false, L"");
  763. }
  764. catch(const exception& e)
  765. {
  766. puts(e.what());
  767. Result = RESULT_PROCESSING_ERROR;
  768. }
  769. #ifndef CONSOLE_TEST
  770. FinalizeChild(Child);
  771. #endif
  772. SetConsoleTitle(SavedTitle);
  773. SetConsoleCP(SavedConsoleCP);
  774. SetConsoleOutputCP(SavedConsoleOutputCP);
  775. }
  776. catch(const exception& e)
  777. {
  778. puts(e.what());
  779. Result = RESULT_INIT_ERROR;
  780. }
  781. FinalizeConsole(InstanceName, RequestEvent, ResponseEvent,
  782. CancelEvent, FileMapping, Job);
  783. }
  784. catch(const exception& e)
  785. {
  786. puts(e.what());
  787. Result = RESULT_GLOBAL_ERROR;
  788. }
  789. return Result;
  790. }
  791. //---------------------------------------------------------------------------