Main.cpp 26 KB

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