Main.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  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. unsigned int Remaining = Timer;
  436. const unsigned int Step = 1000;
  437. const int FirstKey = VK_LBUTTON; // 0x01
  438. const int LastKey = VK_OEM_CLEAR; // 0xFE
  439. // reset key state
  440. for (int Key = FirstKey; Key <= LastKey; Key++)
  441. {
  442. GetAsyncKeyState(Key);
  443. }
  444. while (Remaining > 0)
  445. {
  446. unsigned long WaitResult = WaitForSingleObject(InputTimerEvent, Step);
  447. if (WaitResult == WAIT_OBJECT_0)
  448. {
  449. // input entered
  450. Remaining = 0;
  451. }
  452. else if (WaitResult == WAIT_TIMEOUT)
  453. {
  454. bool Input = false;
  455. for (int Key = FirstKey; Key <= LastKey; Key++)
  456. {
  457. if ((GetAsyncKeyState(Key) & 0x01) != 0)
  458. {
  459. Input = true;
  460. // Finishing the loop nevertheless to reset state of all keys
  461. }
  462. }
  463. if (Input)
  464. {
  465. // If we have new input, reset timer
  466. Remaining = Timer;
  467. }
  468. else if (Remaining > Step)
  469. {
  470. Remaining -= Step;
  471. }
  472. else
  473. {
  474. BreakInput();
  475. Remaining = 0;
  476. }
  477. }
  478. else
  479. {
  480. // abort input on (unlikely) error
  481. BreakInput();
  482. Remaining = 0;
  483. }
  484. }
  485. return 0;
  486. }
  487. //---------------------------------------------------------------------------
  488. void ProcessInputEvent(TConsoleCommStruct::TInputEvent& Event)
  489. {
  490. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE))
  491. {
  492. unsigned long Bytes = 0;
  493. unsigned long Read;
  494. bool Result;
  495. char Ch;
  496. char Buf[LENOF(Event.Str) * 3];
  497. while (((Result = (ReadFile(ConsoleInput, &Ch, 1, &Read, NULL) != 0)) != false) &&
  498. (Read > 0) && (Bytes < LENOF(Buf) - 1) && (Ch != '\n'))
  499. {
  500. if (Ch != '\r')
  501. {
  502. Buf[Bytes] = Ch;
  503. Bytes++;
  504. }
  505. }
  506. Buf[Bytes] = L'\0';
  507. MultiByteToWideChar(CP_UTF8, 0, Buf, -1, Event.Str, LENOF(Event.Str) - 1);
  508. Event.Str[LENOF(Event.Str) - 1] = L'\0';
  509. Print(false, Event.Str);
  510. Print(false, L"\n");
  511. Event.Result = ((Result && (Read > 0)) || (Bytes > 0));
  512. }
  513. else
  514. {
  515. unsigned long PrevMode, NewMode;
  516. GetConsoleMode(ConsoleInput, &PrevMode);
  517. NewMode = PrevMode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
  518. if (Event.Echo)
  519. {
  520. NewMode |= ENABLE_ECHO_INPUT;
  521. }
  522. else
  523. {
  524. NewMode &= ~ENABLE_ECHO_INPUT;
  525. }
  526. SetConsoleMode(ConsoleInput, NewMode);
  527. HANDLE InputTimerThread = NULL;
  528. try
  529. {
  530. if (Event.Timer > 0)
  531. {
  532. unsigned long ThreadId;
  533. InputTimerEvent = CreateEvent(NULL, false, false, NULL);
  534. InputTimerThread = CreateThread(NULL, 0, InputTimerThreadProc,
  535. reinterpret_cast<void *>(Event.Timer), 0, &ThreadId);
  536. }
  537. unsigned long Read;
  538. Event.Result = ReadConsole(ConsoleInput, Event.Str, LENOF(Event.Str) - 1, &Read, NULL);
  539. Event.Str[Read] = L'\0';
  540. bool PendingCancel = (WaitForSingleObject(CancelEvent, 0) == WAIT_OBJECT_0);
  541. if (PendingCancel || !Event.Echo)
  542. {
  543. WriteFile(ConsoleOutput, "\n", 1, NULL, NULL);
  544. Flush();
  545. }
  546. if (PendingCancel || (Read == 0))
  547. {
  548. Event.Result = false;
  549. }
  550. }
  551. __finally
  552. {
  553. if (InputTimerThread != NULL)
  554. {
  555. SetEvent(InputTimerEvent);
  556. WaitForSingleObject(InputTimerThread, 100);
  557. CloseHandle(InputTimerEvent);
  558. InputTimerEvent = NULL;
  559. CloseHandle(InputTimerThread);
  560. }
  561. SetConsoleMode(ConsoleInput, PrevMode);
  562. }
  563. }
  564. }
  565. //---------------------------------------------------------------------------
  566. void ProcessChoiceEvent(TConsoleCommStruct::TChoiceEvent& Event)
  567. {
  568. // note that if output is redirected to file, input is still FILE_TYPE_CHAR
  569. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE))
  570. {
  571. if (Event.Timeouting)
  572. {
  573. Sleep(Event.Timer);
  574. Event.Result = Event.Timeouted;
  575. }
  576. else
  577. {
  578. Event.Result = Event.Break;
  579. }
  580. }
  581. else
  582. {
  583. Event.Result = 0;
  584. unsigned long PrevMode, NewMode;
  585. GetConsoleMode(ConsoleInput, &PrevMode);
  586. NewMode = (PrevMode | ENABLE_PROCESSED_INPUT) & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  587. SetConsoleMode(ConsoleInput, NewMode);
  588. unsigned int ATimer = Event.Timer;
  589. try
  590. {
  591. do
  592. {
  593. unsigned long Read;
  594. INPUT_RECORD Record;
  595. if ((PeekConsoleInput(ConsoleInput, &Record, 1, &Read) != 0) &&
  596. (Read == 1))
  597. {
  598. if ((ReadConsoleInput(ConsoleInput, &Record, 1, &Read) != 0) &&
  599. (Read == 1))
  600. {
  601. bool PendingCancel = (WaitForSingleObject(CancelEvent, 0) == WAIT_OBJECT_0);
  602. if (PendingCancel)
  603. {
  604. Event.Result = Event.Break;
  605. }
  606. else if ((Record.EventType == KEY_EVENT) &&
  607. Record.Event.KeyEvent.bKeyDown)
  608. {
  609. // This happens when Shift key is pressed
  610. if (Record.Event.KeyEvent.uChar.AsciiChar != 0)
  611. {
  612. wchar_t CStr[2];
  613. CStr[0] = Record.Event.KeyEvent.uChar.AsciiChar;
  614. CStr[1] = L'\0';
  615. CharUpperBuff(CStr, 1);
  616. wchar_t C = CStr[0];
  617. if (C == 27)
  618. {
  619. Event.Result = Event.Cancel;
  620. }
  621. else if ((wcschr(Event.Options, C) != NULL) &&
  622. ((Record.Event.KeyEvent.dwControlKeyState &
  623. (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED | LEFT_ALT_PRESSED |
  624. RIGHT_ALT_PRESSED)) == 0))
  625. {
  626. Event.Result = wcschr(Event.Options, C) - Event.Options + 1;
  627. }
  628. }
  629. }
  630. }
  631. }
  632. if (Event.Result == 0)
  633. {
  634. unsigned int TimerSlice = 50;
  635. Sleep(TimerSlice);
  636. if (Event.Timer > 0)
  637. {
  638. if (ATimer > TimerSlice)
  639. {
  640. ATimer -= TimerSlice;
  641. }
  642. else
  643. {
  644. Event.Result = Event.Timeouted;
  645. }
  646. }
  647. }
  648. }
  649. while (Event.Result == 0);
  650. SetConsoleMode(ConsoleInput, PrevMode);
  651. }
  652. catch(...)
  653. {
  654. SetConsoleMode(ConsoleInput, PrevMode);
  655. throw;
  656. }
  657. }
  658. }
  659. //---------------------------------------------------------------------------
  660. inline void ProcessTitleEvent(TConsoleCommStruct::TTitleEvent& Event)
  661. {
  662. SetConsoleTitle(Event.Title);
  663. }
  664. //---------------------------------------------------------------------------
  665. inline void ProcessInitEvent(TConsoleCommStruct::TInitEvent& Event)
  666. {
  667. Event.InputType = InputType;
  668. Event.OutputType = OutputType;
  669. // default anyway
  670. Event.WantsProgress = false;
  671. }
  672. //---------------------------------------------------------------------------
  673. void ProcessEvent(HANDLE ResponseEvent, HANDLE FileMapping)
  674. {
  675. TConsoleCommStruct* CommStruct = GetCommStruct(FileMapping);
  676. try
  677. {
  678. if (CommStruct->Version != TConsoleCommStruct::CurrentVersionConfirmed)
  679. {
  680. throw runtime_error("Incompatible console protocol version");
  681. }
  682. switch (CommStruct->Event)
  683. {
  684. case TConsoleCommStruct::PRINT:
  685. ProcessPrintEvent(CommStruct->PrintEvent);
  686. break;
  687. case TConsoleCommStruct::INPUT:
  688. ProcessInputEvent(CommStruct->InputEvent);
  689. break;
  690. case TConsoleCommStruct::CHOICE:
  691. ProcessChoiceEvent(CommStruct->ChoiceEvent);
  692. break;
  693. case TConsoleCommStruct::TITLE:
  694. ProcessTitleEvent(CommStruct->TitleEvent);
  695. break;
  696. case TConsoleCommStruct::INIT:
  697. ProcessInitEvent(CommStruct->InitEvent);
  698. break;
  699. default:
  700. throw runtime_error("Unknown event");
  701. }
  702. FreeCommStruct(CommStruct);
  703. SetEvent(ResponseEvent);
  704. }
  705. catch(...)
  706. {
  707. FreeCommStruct(CommStruct);
  708. throw;
  709. }
  710. }
  711. //---------------------------------------------------------------------------
  712. BOOL WINAPI HandlerRoutine(DWORD CtrlType)
  713. {
  714. if ((CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_BREAK_EVENT))
  715. {
  716. CancelInput();
  717. return true;
  718. }
  719. else
  720. {
  721. FinalizeChild(Child);
  722. return false;
  723. }
  724. }
  725. //---------------------------------------------------------------------------
  726. #pragma argsused
  727. int wmain(int /*argc*/, wchar_t* /*argv*/[])
  728. {
  729. unsigned long Result = RESULT_UNKNOWN_ERROR;
  730. try
  731. {
  732. randomize();
  733. OSVERSIONINFO VersionInfo;
  734. VersionInfo.dwOSVersionInfoSize = sizeof(VersionInfo);
  735. GetVersionEx(&VersionInfo);
  736. ConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
  737. InputType = GetFileType(ConsoleInput);
  738. SetConsoleCtrlHandler(HandlerRoutine, true);
  739. unsigned int SavedConsoleCP = GetConsoleCP();
  740. unsigned int SavedConsoleOutputCP = GetConsoleOutputCP();
  741. ConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  742. OutputType = GetFileType(ConsoleOutput);
  743. bool SupportsUtf8ConsoleOutput =
  744. ((VersionInfo.dwMajorVersion == 6) && (VersionInfo.dwMinorVersion >= 1)) ||
  745. (VersionInfo.dwMajorVersion > 6);
  746. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE) ||
  747. SupportsUtf8ConsoleOutput)
  748. {
  749. SetConsoleCP(CP_UTF8);
  750. }
  751. else
  752. {
  753. SetConsoleCP(CP_ACP);
  754. }
  755. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE) ||
  756. SupportsUtf8ConsoleOutput)
  757. {
  758. SetConsoleOutputCP(CP_UTF8);
  759. }
  760. else
  761. {
  762. SetConsoleOutputCP(CP_ACP);
  763. }
  764. wchar_t InstanceName[MAX_PATH];
  765. HANDLE RequestEvent, ResponseEvent, FileMapping, Job;
  766. InitializeConsole(InstanceName, RequestEvent, ResponseEvent,
  767. CancelEvent, FileMapping, Job);
  768. wchar_t SavedTitle[512];
  769. GetConsoleTitle(SavedTitle, LENOF(SavedTitle));
  770. try
  771. {
  772. #ifndef CONSOLE_TEST
  773. InitializeChild(GetCommandLine(), InstanceName, Child);
  774. #endif
  775. try
  776. {
  777. bool Continue = true;
  778. do
  779. {
  780. HANDLE Handles[2];
  781. Handles[0] = RequestEvent;
  782. Handles[1] = Child;
  783. unsigned int HandleCount;
  784. #ifndef CONSOLE_TEST
  785. HandleCount = 2;
  786. #else
  787. HandleCount = 1;
  788. #endif
  789. unsigned long WaitResult =
  790. WaitForMultipleObjects(HandleCount, Handles, false, INFINITE);
  791. switch (WaitResult)
  792. {
  793. case WAIT_OBJECT_0:
  794. ProcessEvent(ResponseEvent, FileMapping);
  795. break;
  796. case WAIT_OBJECT_0 + 1:
  797. GetExitCodeProcess(Child, &Result);
  798. CloseHandle(Child);
  799. Child = NULL;
  800. Continue = false;
  801. break;
  802. default:
  803. throw runtime_error("Error waiting for communication from child process.");
  804. }
  805. }
  806. while (Continue);
  807. // flush pending progress message
  808. Print(false, L"");
  809. }
  810. catch(const exception& e)
  811. {
  812. puts(e.what());
  813. Result = RESULT_PROCESSING_ERROR;
  814. }
  815. #ifndef CONSOLE_TEST
  816. FinalizeChild(Child);
  817. #endif
  818. SetConsoleTitle(SavedTitle);
  819. SetConsoleCP(SavedConsoleCP);
  820. SetConsoleOutputCP(SavedConsoleOutputCP);
  821. }
  822. catch(const exception& e)
  823. {
  824. puts(e.what());
  825. Result = RESULT_INIT_ERROR;
  826. }
  827. FinalizeConsole(InstanceName, RequestEvent, ResponseEvent,
  828. CancelEvent, FileMapping, Job);
  829. }
  830. catch(const exception& e)
  831. {
  832. puts(e.what());
  833. Result = RESULT_GLOBAL_ERROR;
  834. }
  835. return Result;
  836. }
  837. //---------------------------------------------------------------------------