Main.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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 >= 1) && (ProductMajor <= 99) &&
  197. (ProductMinor >= 0) && (ProductMinor <= 99) &&
  198. (ProductBuild >= 0) && (ProductBuild <= 99))
  199. {
  200. wsprintf(ProductVersion, L"%d.%d.%d", ProductMajor, ProductMinor, ProductBuild);
  201. }
  202. }
  203. }
  204. delete[] VersionInfo;
  205. }
  206. if (ProductVersion[0] == L'\0')
  207. {
  208. throw runtime_error("Error retrieving product version.");
  209. }
  210. }
  211. //---------------------------------------------------------------------------
  212. void InitializeChild(const wchar_t* CommandLine, const wchar_t* InstanceName, HANDLE& Child)
  213. {
  214. int SkipParam = 0;
  215. wchar_t ChildPath[MAX_PATH] = L"";
  216. size_t CommandLineLen = wcslen(CommandLine);
  217. wchar_t* Buffer = new wchar_t[(CommandLineLen > MAX_PATH ? CommandLineLen : MAX_PATH) + 1];
  218. int Count = 0;
  219. const wchar_t* P = CommandLine;
  220. while (CutToken(P, Buffer))
  221. {
  222. if ((wcschr(L"-/", Buffer[0]) != NULL) &&
  223. (wcsncmpi(Buffer + 1, CONSOLE_CHILD_PARAM, wcslen(CONSOLE_CHILD_PARAM)) == 0) &&
  224. (Buffer[wcslen(CONSOLE_CHILD_PARAM) + 1] == L'='))
  225. {
  226. SkipParam = Count;
  227. wcscpy(ChildPath, Buffer + 1 + wcslen(CONSOLE_CHILD_PARAM) + 1);
  228. }
  229. ++Count;
  230. }
  231. if (wcslen(ChildPath) == 0)
  232. {
  233. DWORD ModuleNameLen = GetModuleFileName(NULL, Buffer, MAX_PATH);
  234. if ((ModuleNameLen == 0) || (ModuleNameLen == MAX_PATH))
  235. {
  236. throw runtime_error("Error retrieving executable name.");
  237. }
  238. const wchar_t* LastDelimiter = wcsrchr(Buffer, L'\\');
  239. const wchar_t* AppFileName;
  240. if (LastDelimiter != NULL)
  241. {
  242. wcsncpy(ChildPath, Buffer, LastDelimiter - Buffer + 1);
  243. ChildPath[LastDelimiter - Buffer + 1] = L'\0';
  244. AppFileName = LastDelimiter + 1;
  245. }
  246. else
  247. {
  248. ChildPath[0] = L'\0';
  249. AppFileName = Buffer;
  250. }
  251. const wchar_t* ExtensionStart = wcsrchr(AppFileName, L'.');
  252. if (ExtensionStart != NULL)
  253. {
  254. wchar_t* End = ChildPath + wcslen(ChildPath);
  255. wcsncpy(End, AppFileName, ExtensionStart - AppFileName);
  256. *(End + (ExtensionStart - AppFileName)) = L'\0';
  257. }
  258. else
  259. {
  260. wcscat(ChildPath, AppFileName);
  261. }
  262. wcscat(ChildPath, L".exe");
  263. }
  264. wchar_t ProductVersion[32];
  265. GetProductVersion(ProductVersion);
  266. wchar_t* Parameters = new wchar_t[(CommandLineLen * 2) + 100 + (Count * 3) + 1];
  267. wsprintf(Parameters, L"\"%s\" /console=%s /consoleinstance=%s ", ChildPath, ProductVersion, InstanceName);
  268. P = CommandLine;
  269. // skip executable path
  270. CutToken(P, Buffer);
  271. int i = 1;
  272. while (CutToken(P, Buffer))
  273. {
  274. if (i != SkipParam)
  275. {
  276. wcscat(Parameters, L"\"");
  277. wchar_t* P2 = Parameters + wcslen(Parameters);
  278. const wchar_t* P3 = Buffer;
  279. const wchar_t* BufferEnd = Buffer + wcslen(Buffer) + 1;
  280. while (P3 != BufferEnd)
  281. {
  282. *P2 = *P3;
  283. ++P2;
  284. if (*P3 == L'"')
  285. {
  286. *P2 = L'"';
  287. ++P2;
  288. }
  289. ++P3;
  290. }
  291. wcscat(Parameters, L"\" ");
  292. }
  293. ++i;
  294. }
  295. delete[] Buffer;
  296. STARTUPINFO StartupInfo = { sizeof(STARTUPINFO) };
  297. PROCESS_INFORMATION ProcessInfomation;
  298. BOOL Result =
  299. CreateProcess(ChildPath, Parameters, NULL, NULL, false, 0, NULL, NULL,
  300. &StartupInfo, &ProcessInfomation);
  301. delete[] Parameters;
  302. if (Result)
  303. {
  304. Child = ProcessInfomation.hProcess;
  305. }
  306. else
  307. {
  308. throw runtime_error("Cannot start WinSCP application.");
  309. }
  310. }
  311. //---------------------------------------------------------------------------
  312. void FinalizeChild(HANDLE Child)
  313. {
  314. if (Child != NULL)
  315. {
  316. TerminateProcess(Child, 0);
  317. CloseHandle(Child);
  318. }
  319. }
  320. //---------------------------------------------------------------------------
  321. void FinalizeConsole(const wchar_t* /*InstanceName*/, HANDLE RequestEvent,
  322. HANDLE ResponseEvent, HANDLE CancelEvent, HANDLE FileMapping, HANDLE Job)
  323. {
  324. CloseHandle(RequestEvent);
  325. CloseHandle(ResponseEvent);
  326. CloseHandle(CancelEvent);
  327. CloseHandle(FileMapping);
  328. if (Job != NULL)
  329. {
  330. CloseHandle(Job);
  331. }
  332. }
  333. //---------------------------------------------------------------------------
  334. static wchar_t LastFromBeginning[sizeof(TConsoleCommStruct::TPrintEvent)] = L""; //???
  335. //---------------------------------------------------------------------------
  336. inline void Flush()
  337. {
  338. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE))
  339. {
  340. fflush(stdout);
  341. }
  342. }
  343. //---------------------------------------------------------------------------
  344. void Print(const wchar_t* Message)
  345. {
  346. int Size = WideCharToMultiByte(CP_UTF8, 0, Message, -1, 0, 0, 0, 0);
  347. if (Size > 0)
  348. {
  349. char* Buffer = new char[(Size * 2) + 1];
  350. if (WideCharToMultiByte(CP_UTF8, 0, Message, -1, Buffer, Size, 0, 0) > 0)
  351. {
  352. Buffer[Size] = '\0';
  353. char* Ptr = Buffer;
  354. while ((Ptr = strchr(Ptr, '\n')) != NULL)
  355. {
  356. memmove(Ptr + 1, Ptr, strlen(Ptr) + 1);
  357. *Ptr = '\r';
  358. Ptr += 2;
  359. }
  360. unsigned long Written;
  361. WriteFile(ConsoleOutput, Buffer, strlen(Buffer), &Written, NULL);
  362. }
  363. delete[] Buffer;
  364. }
  365. }
  366. //---------------------------------------------------------------------------
  367. void Print(bool FromBeginning, const wchar_t* Message)
  368. {
  369. size_t Len = wcslen(Message);
  370. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE))
  371. {
  372. if (FromBeginning && (Message[0] != L'\n'))
  373. {
  374. wcscpy(LastFromBeginning, Message);
  375. }
  376. else
  377. {
  378. if (LastFromBeginning[0] != L'\0')
  379. {
  380. Print(LastFromBeginning);
  381. LastFromBeginning[0] = L'\0';
  382. }
  383. if (FromBeginning && (Message[0] == L'\n'))
  384. {
  385. Print(L"\n");
  386. wcscpy(LastFromBeginning, Message + 1);
  387. }
  388. else
  389. {
  390. Print(Message);
  391. }
  392. Flush();
  393. }
  394. }
  395. else
  396. {
  397. unsigned long Written;
  398. if (FromBeginning)
  399. {
  400. WriteConsole(ConsoleOutput, L"\r", 1, &Written, NULL);
  401. }
  402. bool WriteResult =
  403. WriteConsole(ConsoleOutput, Message, Len, &Written, NULL);
  404. int Error = GetLastError();
  405. // The current console font does not support some characters in the message,
  406. // fall back to ansi-writting
  407. if (!WriteResult && (Error == ERROR_GEN_FAILURE))
  408. {
  409. int Size = WideCharToMultiByte(CP_ACP, 0, Message, -1, 0, 0, 0, 0);
  410. if (Size > 0)
  411. {
  412. char* Buffer = new char[Size];
  413. if (WideCharToMultiByte(CP_ACP, 0, Message, -1, Buffer, Size, 0, 0) > 0)
  414. {
  415. WriteConsoleA(ConsoleOutput, Buffer, strlen(Buffer), &Written, NULL);
  416. }
  417. delete[] Buffer;
  418. }
  419. }
  420. }
  421. }
  422. //---------------------------------------------------------------------------
  423. inline void ProcessPrintEvent(TConsoleCommStruct::TPrintEvent& Event)
  424. {
  425. Print(Event.FromBeginning, Event.Message);
  426. }
  427. //---------------------------------------------------------------------------
  428. void CancelInput()
  429. {
  430. SetEvent(CancelEvent);
  431. }
  432. //---------------------------------------------------------------------------
  433. void BreakInput()
  434. {
  435. FlushConsoleInputBuffer(ConsoleInput);
  436. INPUT_RECORD InputRecord;
  437. memset(&InputRecord, 0, sizeof(InputRecord));
  438. InputRecord.EventType = KEY_EVENT;
  439. InputRecord.Event.KeyEvent.bKeyDown = true;
  440. InputRecord.Event.KeyEvent.wRepeatCount = 1;
  441. InputRecord.Event.KeyEvent.uChar.UnicodeChar = L'\r';
  442. unsigned long Written;
  443. WriteConsoleInput(ConsoleInput, &InputRecord, 1, &Written);
  444. CancelInput();
  445. }
  446. //---------------------------------------------------------------------------
  447. DWORD WINAPI InputTimerThreadProc(void* Parameter)
  448. {
  449. unsigned int Timer = reinterpret_cast<unsigned int>(Parameter);
  450. unsigned int Remaining = Timer;
  451. const unsigned int Step = 1000;
  452. const int FirstKey = VK_LBUTTON; // 0x01
  453. const int LastKey = VK_OEM_CLEAR; // 0xFE
  454. // reset key state
  455. for (int Key = FirstKey; Key <= LastKey; Key++)
  456. {
  457. GetAsyncKeyState(Key);
  458. }
  459. while (Remaining > 0)
  460. {
  461. unsigned long WaitResult = WaitForSingleObject(InputTimerEvent, Step);
  462. if (WaitResult == WAIT_OBJECT_0)
  463. {
  464. // input entered
  465. Remaining = 0;
  466. }
  467. else if (WaitResult == WAIT_TIMEOUT)
  468. {
  469. bool Input = false;
  470. for (int Key = FirstKey; Key <= LastKey; Key++)
  471. {
  472. if ((GetAsyncKeyState(Key) & 0x01) != 0)
  473. {
  474. Input = true;
  475. // Finishing the loop nevertheless to reset state of all keys
  476. }
  477. }
  478. if (Input)
  479. {
  480. // If we have new input, reset timer
  481. Remaining = Timer;
  482. }
  483. else if (Remaining > Step)
  484. {
  485. Remaining -= Step;
  486. }
  487. else
  488. {
  489. BreakInput();
  490. Remaining = 0;
  491. }
  492. }
  493. else
  494. {
  495. // abort input on (unlikely) error
  496. BreakInput();
  497. Remaining = 0;
  498. }
  499. }
  500. return 0;
  501. }
  502. //---------------------------------------------------------------------------
  503. void ProcessInputEvent(TConsoleCommStruct::TInputEvent& Event)
  504. {
  505. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE))
  506. {
  507. unsigned long Bytes = 0;
  508. unsigned long Read;
  509. bool Result;
  510. char Ch;
  511. char Buf[LENOF(Event.Str) * 3];
  512. while (((Result = (ReadFile(ConsoleInput, &Ch, 1, &Read, NULL) != 0)) != false) &&
  513. (Read > 0) && (Bytes < LENOF(Buf) - 1) && (Ch != '\n'))
  514. {
  515. if (Ch != '\r')
  516. {
  517. Buf[Bytes] = Ch;
  518. Bytes++;
  519. }
  520. }
  521. Buf[Bytes] = L'\0';
  522. MultiByteToWideChar(CP_UTF8, 0, Buf, -1, Event.Str, LENOF(Event.Str) - 1);
  523. Event.Str[LENOF(Event.Str) - 1] = L'\0';
  524. Print(false, Event.Str);
  525. Print(false, L"\n");
  526. Event.Result = ((Result && (Read > 0)) || (Bytes > 0));
  527. }
  528. else
  529. {
  530. unsigned long PrevMode, NewMode;
  531. GetConsoleMode(ConsoleInput, &PrevMode);
  532. NewMode = PrevMode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
  533. if (Event.Echo)
  534. {
  535. NewMode |= ENABLE_ECHO_INPUT;
  536. }
  537. else
  538. {
  539. NewMode &= ~ENABLE_ECHO_INPUT;
  540. }
  541. SetConsoleMode(ConsoleInput, NewMode);
  542. HANDLE InputTimerThread = NULL;
  543. try
  544. {
  545. if (Event.Timer > 0)
  546. {
  547. unsigned long ThreadId;
  548. InputTimerEvent = CreateEvent(NULL, false, false, NULL);
  549. InputTimerThread = CreateThread(NULL, 0, InputTimerThreadProc,
  550. reinterpret_cast<void *>(Event.Timer), 0, &ThreadId);
  551. }
  552. unsigned long Read;
  553. Event.Result = ReadConsole(ConsoleInput, Event.Str, LENOF(Event.Str) - 1, &Read, NULL);
  554. Event.Str[Read] = L'\0';
  555. bool PendingCancel = (WaitForSingleObject(CancelEvent, 0) == WAIT_OBJECT_0);
  556. if (PendingCancel || !Event.Echo)
  557. {
  558. WriteFile(ConsoleOutput, "\n", 1, NULL, NULL);
  559. Flush();
  560. }
  561. if (PendingCancel || (Read == 0))
  562. {
  563. Event.Result = false;
  564. }
  565. }
  566. __finally
  567. {
  568. if (InputTimerThread != NULL)
  569. {
  570. SetEvent(InputTimerEvent);
  571. WaitForSingleObject(InputTimerThread, 100);
  572. CloseHandle(InputTimerEvent);
  573. InputTimerEvent = NULL;
  574. CloseHandle(InputTimerThread);
  575. }
  576. SetConsoleMode(ConsoleInput, PrevMode);
  577. }
  578. }
  579. }
  580. //---------------------------------------------------------------------------
  581. void ProcessChoiceEvent(TConsoleCommStruct::TChoiceEvent& Event)
  582. {
  583. // note that if output is redirected to file, input is still FILE_TYPE_CHAR
  584. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE))
  585. {
  586. if (Event.Timeouting)
  587. {
  588. Sleep(Event.Timer);
  589. Event.Result = Event.Timeouted;
  590. }
  591. else
  592. {
  593. Event.Result = Event.Break;
  594. }
  595. }
  596. else
  597. {
  598. Event.Result = 0;
  599. unsigned long PrevMode, NewMode;
  600. GetConsoleMode(ConsoleInput, &PrevMode);
  601. NewMode = (PrevMode | ENABLE_PROCESSED_INPUT) & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  602. SetConsoleMode(ConsoleInput, NewMode);
  603. unsigned int ATimer = Event.Timer;
  604. try
  605. {
  606. do
  607. {
  608. unsigned long Read;
  609. INPUT_RECORD Record;
  610. if ((PeekConsoleInput(ConsoleInput, &Record, 1, &Read) != 0) &&
  611. (Read == 1))
  612. {
  613. if ((ReadConsoleInput(ConsoleInput, &Record, 1, &Read) != 0) &&
  614. (Read == 1))
  615. {
  616. bool PendingCancel = (WaitForSingleObject(CancelEvent, 0) == WAIT_OBJECT_0);
  617. if (PendingCancel)
  618. {
  619. Event.Result = Event.Break;
  620. }
  621. else if ((Record.EventType == KEY_EVENT) &&
  622. Record.Event.KeyEvent.bKeyDown)
  623. {
  624. // This happens when Shift key is pressed
  625. if (Record.Event.KeyEvent.uChar.AsciiChar != 0)
  626. {
  627. wchar_t CStr[2];
  628. CStr[0] = Record.Event.KeyEvent.uChar.AsciiChar;
  629. CStr[1] = L'\0';
  630. CharUpperBuff(CStr, 1);
  631. wchar_t C = CStr[0];
  632. if (C == 27)
  633. {
  634. Event.Result = Event.Cancel;
  635. }
  636. else if ((wcschr(Event.Options, C) != NULL) &&
  637. ((Record.Event.KeyEvent.dwControlKeyState &
  638. (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED | LEFT_ALT_PRESSED |
  639. RIGHT_ALT_PRESSED)) == 0))
  640. {
  641. Event.Result = wcschr(Event.Options, C) - Event.Options + 1;
  642. }
  643. }
  644. }
  645. }
  646. }
  647. if (Event.Result == 0)
  648. {
  649. unsigned int TimerSlice = 50;
  650. Sleep(TimerSlice);
  651. if (Event.Timer > 0)
  652. {
  653. if (ATimer > TimerSlice)
  654. {
  655. ATimer -= TimerSlice;
  656. }
  657. else
  658. {
  659. Event.Result = Event.Timeouted;
  660. }
  661. }
  662. }
  663. }
  664. while (Event.Result == 0);
  665. SetConsoleMode(ConsoleInput, PrevMode);
  666. }
  667. catch(...)
  668. {
  669. SetConsoleMode(ConsoleInput, PrevMode);
  670. throw;
  671. }
  672. }
  673. }
  674. //---------------------------------------------------------------------------
  675. inline void ProcessTitleEvent(TConsoleCommStruct::TTitleEvent& Event)
  676. {
  677. SetConsoleTitle(Event.Title);
  678. }
  679. //---------------------------------------------------------------------------
  680. inline void ProcessInitEvent(TConsoleCommStruct::TInitEvent& Event)
  681. {
  682. Event.InputType = InputType;
  683. Event.OutputType = OutputType;
  684. // default anyway
  685. Event.WantsProgress = false;
  686. }
  687. //---------------------------------------------------------------------------
  688. void ProcessEvent(HANDLE ResponseEvent, HANDLE FileMapping)
  689. {
  690. TConsoleCommStruct* CommStruct = GetCommStruct(FileMapping);
  691. try
  692. {
  693. if (CommStruct->Version != TConsoleCommStruct::CurrentVersionConfirmed)
  694. {
  695. throw runtime_error("Incompatible console protocol version");
  696. }
  697. switch (CommStruct->Event)
  698. {
  699. case TConsoleCommStruct::PRINT:
  700. ProcessPrintEvent(CommStruct->PrintEvent);
  701. break;
  702. case TConsoleCommStruct::INPUT:
  703. ProcessInputEvent(CommStruct->InputEvent);
  704. break;
  705. case TConsoleCommStruct::CHOICE:
  706. ProcessChoiceEvent(CommStruct->ChoiceEvent);
  707. break;
  708. case TConsoleCommStruct::TITLE:
  709. ProcessTitleEvent(CommStruct->TitleEvent);
  710. break;
  711. case TConsoleCommStruct::INIT:
  712. ProcessInitEvent(CommStruct->InitEvent);
  713. break;
  714. default:
  715. throw runtime_error("Unknown event");
  716. }
  717. FreeCommStruct(CommStruct);
  718. SetEvent(ResponseEvent);
  719. }
  720. catch(...)
  721. {
  722. FreeCommStruct(CommStruct);
  723. throw;
  724. }
  725. }
  726. //---------------------------------------------------------------------------
  727. BOOL WINAPI HandlerRoutine(DWORD CtrlType)
  728. {
  729. if ((CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_BREAK_EVENT))
  730. {
  731. CancelInput();
  732. return true;
  733. }
  734. else
  735. {
  736. FinalizeChild(Child);
  737. return false;
  738. }
  739. }
  740. //---------------------------------------------------------------------------
  741. #pragma argsused
  742. int wmain(int /*argc*/, wchar_t* /*argv*/[])
  743. {
  744. unsigned long Result = RESULT_UNKNOWN_ERROR;
  745. try
  746. {
  747. randomize();
  748. OSVERSIONINFO VersionInfo;
  749. VersionInfo.dwOSVersionInfoSize = sizeof(VersionInfo);
  750. GetVersionEx(&VersionInfo);
  751. ConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
  752. InputType = GetFileType(ConsoleInput);
  753. SetConsoleCtrlHandler(HandlerRoutine, true);
  754. unsigned int SavedConsoleCP = GetConsoleCP();
  755. unsigned int SavedConsoleOutputCP = GetConsoleOutputCP();
  756. ConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  757. OutputType = GetFileType(ConsoleOutput);
  758. bool SupportsUtf8ConsoleOutput =
  759. ((VersionInfo.dwMajorVersion == 6) && (VersionInfo.dwMinorVersion >= 1)) ||
  760. (VersionInfo.dwMajorVersion > 6);
  761. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE) ||
  762. SupportsUtf8ConsoleOutput)
  763. {
  764. SetConsoleCP(CP_UTF8);
  765. }
  766. else
  767. {
  768. SetConsoleCP(CP_ACP);
  769. }
  770. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE) ||
  771. SupportsUtf8ConsoleOutput)
  772. {
  773. SetConsoleOutputCP(CP_UTF8);
  774. }
  775. else
  776. {
  777. SetConsoleOutputCP(CP_ACP);
  778. }
  779. wchar_t InstanceName[MAX_PATH];
  780. HANDLE RequestEvent, ResponseEvent, FileMapping, Job;
  781. InitializeConsole(InstanceName, RequestEvent, ResponseEvent,
  782. CancelEvent, FileMapping, Job);
  783. wchar_t SavedTitle[512];
  784. GetConsoleTitle(SavedTitle, LENOF(SavedTitle));
  785. try
  786. {
  787. #ifndef CONSOLE_TEST
  788. InitializeChild(GetCommandLine(), InstanceName, Child);
  789. #endif
  790. try
  791. {
  792. bool Continue = true;
  793. do
  794. {
  795. HANDLE Handles[2];
  796. Handles[0] = RequestEvent;
  797. Handles[1] = Child;
  798. unsigned int HandleCount;
  799. #ifndef CONSOLE_TEST
  800. HandleCount = 2;
  801. #else
  802. HandleCount = 1;
  803. #endif
  804. unsigned long WaitResult =
  805. WaitForMultipleObjects(HandleCount, Handles, false, INFINITE);
  806. switch (WaitResult)
  807. {
  808. case WAIT_OBJECT_0:
  809. ProcessEvent(ResponseEvent, FileMapping);
  810. break;
  811. case WAIT_OBJECT_0 + 1:
  812. GetExitCodeProcess(Child, &Result);
  813. CloseHandle(Child);
  814. Child = NULL;
  815. Continue = false;
  816. break;
  817. default:
  818. throw runtime_error("Error waiting for communication from child process.");
  819. }
  820. }
  821. while (Continue);
  822. // flush pending progress message
  823. Print(false, L"");
  824. }
  825. catch(const exception& e)
  826. {
  827. puts(e.what());
  828. Result = RESULT_PROCESSING_ERROR;
  829. }
  830. #ifndef CONSOLE_TEST
  831. FinalizeChild(Child);
  832. #endif
  833. SetConsoleTitle(SavedTitle);
  834. SetConsoleCP(SavedConsoleCP);
  835. SetConsoleOutputCP(SavedConsoleOutputCP);
  836. }
  837. catch(const exception& e)
  838. {
  839. puts(e.what());
  840. Result = RESULT_INIT_ERROR;
  841. }
  842. FinalizeConsole(InstanceName, RequestEvent, ResponseEvent,
  843. CancelEvent, FileMapping, Job);
  844. }
  845. catch(const exception& e)
  846. {
  847. puts(e.what());
  848. Result = RESULT_GLOBAL_ERROR;
  849. }
  850. return Result;
  851. }
  852. //---------------------------------------------------------------------------