ConsoleRunner.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <Common.h>
  5. #include <Exceptions.h>
  6. #include <Script.h>
  7. #include <CoreMain.h>
  8. #include <Terminal.h>
  9. #include <PuttyTools.h>
  10. #include <Consts.hpp>
  11. #include "Console.h"
  12. #include "WinInterface.h"
  13. #include "ProgParams.h"
  14. #include "TextsWin.h"
  15. #include "TextsCore.h"
  16. #include "CustomWinConfiguration.h"
  17. #include "SynchronizeController.h"
  18. #include "GUITools.h"
  19. enum { RESULT_SUCCESS = 0, RESULT_ANY_ERROR = 1 };
  20. //---------------------------------------------------------------------------
  21. #define WM_INTERUPT_IDLE (WM_WINSCP_USER + 3)
  22. #define BATCH_INPUT_TIMEOUT 10000
  23. //---------------------------------------------------------------------------
  24. #pragma package(smart_init)
  25. //---------------------------------------------------------------------------
  26. class TConsole
  27. {
  28. public:
  29. virtual __fastcall ~TConsole() {};
  30. virtual void __fastcall Print(AnsiString Str, bool FromBeginning = false) = 0;
  31. virtual bool __fastcall Input(AnsiString & Str, bool Echo, unsigned int Timer) = 0;
  32. virtual int __fastcall Choice(AnsiString Options, int Cancel, int Break,
  33. int Timeouted, unsigned int Timer) = 0;
  34. virtual bool __fastcall PendingAbort() = 0;
  35. virtual void __fastcall SetTitle(AnsiString Title) = 0;
  36. virtual void __fastcall WaitBeforeExit() = 0;
  37. };
  38. //---------------------------------------------------------------------------
  39. class TOwnConsole : public TConsole
  40. {
  41. public:
  42. static TOwnConsole * __fastcall Instance();
  43. virtual void __fastcall Print(AnsiString Str, bool FromBeginning = false);
  44. virtual bool __fastcall Input(AnsiString & Str, bool Echo, unsigned int Timer);
  45. virtual int __fastcall Choice(AnsiString Options, int Cancel, int Break,
  46. int Timeouted, unsigned int Timer);
  47. virtual bool __fastcall PendingAbort();
  48. virtual void __fastcall SetTitle(AnsiString Title);
  49. virtual void __fastcall WaitBeforeExit();
  50. protected:
  51. static TOwnConsole * FInstance;
  52. __fastcall TOwnConsole();
  53. virtual __fastcall ~TOwnConsole();
  54. void __fastcall BreakInput();
  55. static BOOL WINAPI HandlerRoutine(DWORD CtrlType);
  56. static int __fastcall InputTimerThreadProc(void * Parameter);
  57. private:
  58. HANDLE FInput;
  59. HANDLE FOutput;
  60. HANDLE FInputTimerEvent;
  61. static TCriticalSection FSection;
  62. bool FPendingAbort;
  63. };
  64. //---------------------------------------------------------------------------
  65. TOwnConsole * TOwnConsole::FInstance = NULL;
  66. TCriticalSection TOwnConsole::FSection;
  67. //---------------------------------------------------------------------------
  68. __fastcall TOwnConsole::TOwnConsole()
  69. {
  70. assert(FInstance == NULL);
  71. FInstance = this;
  72. AllocConsole();
  73. SetConsoleCtrlHandler(HandlerRoutine, true);
  74. FInput = GetStdHandle(STD_INPUT_HANDLE);
  75. FOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  76. FInputTimerEvent = NULL;
  77. FPendingAbort = false;
  78. }
  79. //---------------------------------------------------------------------------
  80. __fastcall TOwnConsole::~TOwnConsole()
  81. {
  82. TGuard Guard(&FSection);
  83. SetConsoleCtrlHandler(HandlerRoutine, false);
  84. FreeConsole();
  85. assert(FInstance == this);
  86. FInstance = NULL;
  87. }
  88. //---------------------------------------------------------------------------
  89. TOwnConsole * __fastcall TOwnConsole::Instance()
  90. {
  91. return new TOwnConsole();
  92. }
  93. //---------------------------------------------------------------------------
  94. void __fastcall TOwnConsole::BreakInput()
  95. {
  96. FlushConsoleInputBuffer(FInput);
  97. INPUT_RECORD InputRecord;
  98. memset(&InputRecord, 0, sizeof(InputRecord));
  99. InputRecord.EventType = KEY_EVENT;
  100. InputRecord.Event.KeyEvent.bKeyDown = true;
  101. InputRecord.Event.KeyEvent.wRepeatCount = 1;
  102. InputRecord.Event.KeyEvent.uChar.AsciiChar = '\r';
  103. unsigned long Written;
  104. // this assertion occasionally fails (when console is being exited)
  105. CHECK(WriteConsoleInput(FInput, &InputRecord, 1, &Written));
  106. assert(Written == 1);
  107. FPendingAbort = true;
  108. PostMessage(Application->Handle, WM_INTERUPT_IDLE, 0, 0);
  109. }
  110. //---------------------------------------------------------------------------
  111. BOOL WINAPI TOwnConsole::HandlerRoutine(DWORD CtrlType)
  112. {
  113. if ((CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_BREAK_EVENT))
  114. {
  115. {
  116. TGuard Guard(&FSection);
  117. // just to be real thread-safe
  118. if (FInstance != NULL)
  119. {
  120. FInstance->BreakInput();
  121. }
  122. }
  123. return true;
  124. }
  125. else
  126. {
  127. return false;
  128. }
  129. }
  130. //---------------------------------------------------------------------------
  131. int __fastcall TOwnConsole::InputTimerThreadProc(void * Parameter)
  132. {
  133. assert(FInstance != NULL);
  134. unsigned int Timer = reinterpret_cast<unsigned int>(Parameter);
  135. if (WaitForSingleObject(FInstance->FInputTimerEvent, Timer) == WAIT_TIMEOUT)
  136. {
  137. FInstance->BreakInput();
  138. }
  139. return 0;
  140. }
  141. //---------------------------------------------------------------------------
  142. bool __fastcall TOwnConsole::PendingAbort()
  143. {
  144. if (FPendingAbort)
  145. {
  146. FPendingAbort = false;
  147. return true;
  148. }
  149. else
  150. {
  151. return FPendingAbort;
  152. }
  153. }
  154. //---------------------------------------------------------------------------
  155. void __fastcall TOwnConsole::Print(AnsiString Str, bool FromBeginning)
  156. {
  157. if (FromBeginning)
  158. {
  159. CONSOLE_SCREEN_BUFFER_INFO BufferInfo;
  160. GetConsoleScreenBufferInfo(FOutput, &BufferInfo);
  161. BufferInfo.dwCursorPosition.X = 0;
  162. SetConsoleCursorPosition(FOutput, BufferInfo.dwCursorPosition);
  163. }
  164. unsigned long Written;
  165. AnsiToOem(Str);
  166. bool Result = WriteConsole(FOutput, Str.c_str(), Str.Length(), &Written, NULL);
  167. assert(Result);
  168. USEDPARAM(Result);
  169. assert(Str.Length() == static_cast<long>(Written));
  170. }
  171. //---------------------------------------------------------------------------
  172. bool __fastcall TOwnConsole::Input(AnsiString & Str, bool Echo, unsigned int Timer)
  173. {
  174. unsigned long PrevMode, NewMode;
  175. GetConsoleMode(FInput, &PrevMode);
  176. NewMode = PrevMode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
  177. if (Echo)
  178. {
  179. NewMode |= ENABLE_ECHO_INPUT;
  180. }
  181. else
  182. {
  183. NewMode &= ~ENABLE_ECHO_INPUT;
  184. }
  185. SetConsoleMode(FInput, NewMode);
  186. HANDLE InputTimerThread = NULL;
  187. bool Result;
  188. try
  189. {
  190. if (Timer > 0)
  191. {
  192. unsigned int ThreadId;
  193. assert(FInputTimerEvent == NULL);
  194. FInputTimerEvent = CreateEvent(NULL, false, false, NULL);
  195. InputTimerThread = (HANDLE)BeginThread(NULL, 0, InputTimerThreadProc,
  196. reinterpret_cast<void *>(Timer), 0, ThreadId);
  197. }
  198. unsigned long Read;
  199. Str.SetLength(10240);
  200. Result = ReadConsole(FInput, Str.c_str(), Str.Length(), &Read, NULL);
  201. assert(Result);
  202. Str.SetLength(Read);
  203. OemToAnsi(Str);
  204. if (FPendingAbort || !Echo)
  205. {
  206. Print("\n");
  207. }
  208. if (FPendingAbort || (Read == 0))
  209. {
  210. Result = false;
  211. FPendingAbort = false;
  212. }
  213. }
  214. __finally
  215. {
  216. if (InputTimerThread != NULL)
  217. {
  218. SetEvent(FInputTimerEvent);
  219. WaitForSingleObject(InputTimerThread, 100);
  220. CloseHandle(FInputTimerEvent);
  221. FInputTimerEvent = NULL;
  222. CloseHandle(InputTimerThread);
  223. }
  224. SetConsoleMode(FInput, PrevMode);
  225. }
  226. return Result;
  227. }
  228. //---------------------------------------------------------------------------
  229. int __fastcall TOwnConsole::Choice(AnsiString Options, int Cancel, int Break,
  230. int Timeouted, unsigned int Timer)
  231. {
  232. AnsiToOem(Options);
  233. unsigned int ATimer = Timer;
  234. int Result = 0;
  235. unsigned long PrevMode, NewMode;
  236. GetConsoleMode(FInput, &PrevMode);
  237. NewMode = (PrevMode | ENABLE_PROCESSED_INPUT) & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  238. SetConsoleMode(FInput, NewMode);
  239. try
  240. {
  241. do
  242. {
  243. unsigned long Read;
  244. INPUT_RECORD Record;
  245. if ((PeekConsoleInput(FInput, &Record, 1, &Read) != 0) &&
  246. (Read == 1))
  247. {
  248. if ((ReadConsoleInput(FInput, &Record, 1, &Read) != 0) &&
  249. (Read == 1))
  250. {
  251. if (PendingAbort())
  252. {
  253. Result = Break;
  254. }
  255. else if ((Record.EventType == KEY_EVENT) &&
  256. Record.Event.KeyEvent.bKeyDown)
  257. {
  258. char C = AnsiUpperCase(Record.Event.KeyEvent.uChar.AsciiChar)[1];
  259. if (C == 27)
  260. {
  261. Result = Cancel;
  262. }
  263. else if ((Options.Pos(C) > 0) &&
  264. FLAGCLEAR(Record.Event.KeyEvent.dwControlKeyState,
  265. LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED | LEFT_ALT_PRESSED |
  266. RIGHT_CTRL_PRESSED))
  267. {
  268. Result = Options.Pos(C);
  269. }
  270. }
  271. }
  272. }
  273. if (Result == 0)
  274. {
  275. unsigned int TimerSlice = 50;
  276. Sleep(TimerSlice);
  277. if (Timer > 0)
  278. {
  279. if (ATimer > TimerSlice)
  280. {
  281. ATimer -= TimerSlice;
  282. }
  283. else
  284. {
  285. Result = Timeouted;
  286. }
  287. }
  288. }
  289. }
  290. while (Result == 0);
  291. }
  292. __finally
  293. {
  294. SetConsoleMode(FInput, PrevMode);
  295. }
  296. return Result;
  297. }
  298. //---------------------------------------------------------------------------
  299. void __fastcall TOwnConsole::SetTitle(AnsiString Title)
  300. {
  301. AnsiToOem(Title);
  302. SetConsoleTitle(Title.c_str());
  303. }
  304. //---------------------------------------------------------------------------
  305. void __fastcall TOwnConsole::WaitBeforeExit()
  306. {
  307. unsigned long Read;
  308. INPUT_RECORD Record;
  309. while (ReadConsoleInput(FInput, &Record, 1, &Read))
  310. {
  311. if ((Read == 1) && (Record.EventType == KEY_EVENT) &&
  312. (Record.Event.KeyEvent.uChar.AsciiChar != 0) &&
  313. Record.Event.KeyEvent.bKeyDown)
  314. {
  315. break;
  316. }
  317. }
  318. }
  319. //---------------------------------------------------------------------------
  320. class TExternalConsole : public TConsole
  321. {
  322. public:
  323. __fastcall TExternalConsole(const AnsiString Instance);
  324. virtual __fastcall ~TExternalConsole();
  325. virtual void __fastcall Print(AnsiString Str, bool FromBeginning = false);
  326. virtual bool __fastcall Input(AnsiString & Str, bool Echo, unsigned int Timer);
  327. virtual int __fastcall Choice(AnsiString Options, int Cancel, int Break,
  328. int Timeouted, unsigned int Timer);
  329. virtual bool __fastcall PendingAbort();
  330. virtual void __fastcall SetTitle(AnsiString Title);
  331. virtual void __fastcall WaitBeforeExit();
  332. private:
  333. bool FPendingAbort;
  334. HANDLE FRequestEvent;
  335. HANDLE FResponseEvent;
  336. HANDLE FCancelEvent;
  337. HANDLE FFileMapping;
  338. static const int PrintTimeout = 5000;
  339. inline TConsoleCommStruct * __fastcall GetCommStruct();
  340. inline void __fastcall FreeCommStruct(TConsoleCommStruct * CommStruct);
  341. inline void __fastcall SendEvent(int Timeout);
  342. };
  343. //---------------------------------------------------------------------------
  344. __fastcall TExternalConsole::TExternalConsole(const AnsiString Instance)
  345. {
  346. FRequestEvent = OpenEvent(EVENT_ALL_ACCESS, false,
  347. FORMAT("%s%s", (CONSOLE_EVENT_REQUEST, (Instance))).c_str());
  348. FResponseEvent = OpenEvent(EVENT_ALL_ACCESS, false,
  349. FORMAT("%s%s", (CONSOLE_EVENT_RESPONSE, (Instance))).c_str());
  350. FCancelEvent = OpenEvent(EVENT_ALL_ACCESS, false,
  351. FORMAT("%s%s", (CONSOLE_EVENT_CANCEL, (Instance))).c_str());
  352. FFileMapping = OpenFileMapping(FILE_MAP_ALL_ACCESS, false,
  353. FORMAT("%s%s", (CONSOLE_MAPPING, (Instance))).c_str());
  354. if ((FRequestEvent == NULL) || (FResponseEvent == NULL) || (FFileMapping == NULL))
  355. {
  356. throw Exception(LoadStr(EXTERNAL_CONSOLE_INIT_ERROR));
  357. }
  358. TConsoleCommStruct * CommStruct = GetCommStruct();
  359. try
  360. {
  361. if (CommStruct->Version < TConsoleCommStruct::MinVersion)
  362. {
  363. throw Exception(FMTLOAD(EXTERNAL_CONSOLE_INCOMPATIBLE, (CommStruct->Version)));
  364. }
  365. else if (CommStruct->Version == TConsoleCommStruct::Version1)
  366. {
  367. // version upgrade from 1 to the latest version indicates to the
  368. // external console that the application supports newer versions than 0.
  369. CommStruct->Version = TConsoleCommStruct::CurrentVersion;
  370. }
  371. else if (CommStruct->Version > TConsoleCommStruct::CurrentVersion)
  372. {
  373. CommStruct->Version = TConsoleCommStruct::CurrentVersion;
  374. }
  375. }
  376. __finally
  377. {
  378. FreeCommStruct(CommStruct);
  379. }
  380. // to break application event loop regularly during "watching for changes"
  381. // to allow user to abort it
  382. SetTimer(Application->Handle, 1, 500, NULL);
  383. }
  384. //---------------------------------------------------------------------------
  385. __fastcall TExternalConsole::~TExternalConsole()
  386. {
  387. CloseHandle(FRequestEvent);
  388. CloseHandle(FResponseEvent);
  389. CloseHandle(FCancelEvent);
  390. CloseHandle(FFileMapping);
  391. KillTimer(Application->Handle, 1);
  392. }
  393. //---------------------------------------------------------------------------
  394. TConsoleCommStruct * __fastcall TExternalConsole::GetCommStruct()
  395. {
  396. TConsoleCommStruct * Result;
  397. Result = static_cast<TConsoleCommStruct*>(MapViewOfFile(FFileMapping,
  398. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  399. if (Result == NULL)
  400. {
  401. throw Exception(LoadStr(CONSOLE_COMM_ERROR));
  402. }
  403. return Result;
  404. }
  405. //---------------------------------------------------------------------------
  406. void __fastcall TExternalConsole::FreeCommStruct(TConsoleCommStruct * CommStruct)
  407. {
  408. UnmapViewOfFile(CommStruct);
  409. }
  410. //---------------------------------------------------------------------------
  411. void __fastcall TExternalConsole::SendEvent(int Timeout)
  412. {
  413. SetEvent(FRequestEvent);
  414. if (WaitForSingleObject(FResponseEvent, Timeout) != WAIT_OBJECT_0)
  415. {
  416. throw Exception(LoadStr(CONSOLE_SEND_TIMEOUT));
  417. }
  418. }
  419. //---------------------------------------------------------------------------
  420. void __fastcall TExternalConsole::Print(AnsiString Str, bool FromBeginning)
  421. {
  422. TConsoleCommStruct * CommStruct = GetCommStruct();
  423. try
  424. {
  425. if (Str.Length() >= sizeof(CommStruct->PrintEvent.Message))
  426. {
  427. throw Exception(FMTLOAD(CONSOLE_PRINT_TOO_LONG, (Str.Length())));
  428. }
  429. CommStruct->Event = TConsoleCommStruct::PRINT;
  430. CharToOem(Str.c_str(), CommStruct->PrintEvent.Message);
  431. CommStruct->PrintEvent.FromBeginning = FromBeginning;
  432. }
  433. __finally
  434. {
  435. FreeCommStruct(CommStruct);
  436. }
  437. SendEvent(PrintTimeout);
  438. }
  439. //---------------------------------------------------------------------------
  440. bool __fastcall TExternalConsole::Input(AnsiString & Str, bool Echo, unsigned int Timer)
  441. {
  442. TConsoleCommStruct * CommStruct = GetCommStruct();
  443. try
  444. {
  445. CommStruct->Event = TConsoleCommStruct::INPUT;
  446. CommStruct->InputEvent.Echo = Echo;
  447. CommStruct->InputEvent.Result = false;
  448. CommStruct->InputEvent.Str[0] = '\0';
  449. if (CommStruct->Version >= TConsoleCommStruct::Version2)
  450. {
  451. CommStruct->InputEvent.Timer = Timer;
  452. }
  453. }
  454. __finally
  455. {
  456. FreeCommStruct(CommStruct);
  457. }
  458. SendEvent(INFINITE);
  459. bool Result;
  460. CommStruct = GetCommStruct();
  461. try
  462. {
  463. Result = CommStruct->InputEvent.Result;
  464. Str.SetLength(strlen(CommStruct->InputEvent.Str));
  465. OemToChar(CommStruct->InputEvent.Str, Str.c_str());
  466. }
  467. __finally
  468. {
  469. FreeCommStruct(CommStruct);
  470. }
  471. return Result;
  472. }
  473. //---------------------------------------------------------------------------
  474. int __fastcall TExternalConsole::Choice(AnsiString Options, int Cancel, int Break,
  475. int Timeouted, unsigned int Timer)
  476. {
  477. TConsoleCommStruct * CommStruct = GetCommStruct();
  478. try
  479. {
  480. CommStruct->Event = TConsoleCommStruct::CHOICE;
  481. assert(Options.Length() < sizeof(CommStruct->ChoiceEvent.Options));
  482. CharToOem(Options.c_str(), CommStruct->ChoiceEvent.Options);
  483. CommStruct->ChoiceEvent.Cancel = Cancel;
  484. CommStruct->ChoiceEvent.Break = Break;
  485. CommStruct->ChoiceEvent.Result = Break;
  486. if (CommStruct->Version >= TConsoleCommStruct::Version2)
  487. {
  488. CommStruct->ChoiceEvent.Timeouted = Timeouted;
  489. CommStruct->ChoiceEvent.Timer = Timer;
  490. }
  491. }
  492. __finally
  493. {
  494. FreeCommStruct(CommStruct);
  495. }
  496. SendEvent(INFINITE);
  497. int Result;
  498. CommStruct = GetCommStruct();
  499. try
  500. {
  501. Result = CommStruct->ChoiceEvent.Result;
  502. }
  503. __finally
  504. {
  505. FreeCommStruct(CommStruct);
  506. }
  507. return Result;
  508. }
  509. //---------------------------------------------------------------------------
  510. bool __fastcall TExternalConsole::PendingAbort()
  511. {
  512. return (WaitForSingleObject(FCancelEvent, 0) == WAIT_OBJECT_0);
  513. }
  514. //---------------------------------------------------------------------------
  515. void __fastcall TExternalConsole::SetTitle(AnsiString Title)
  516. {
  517. TConsoleCommStruct * CommStruct = GetCommStruct();
  518. try
  519. {
  520. if (Title.Length() >= sizeof(CommStruct->TitleEvent.Title))
  521. {
  522. throw Exception(FMTLOAD(CONSOLE_PRINT_TOO_LONG, (Title.Length())));
  523. }
  524. CommStruct->Event = TConsoleCommStruct::TITLE;
  525. CharToOem(Title.c_str(), CommStruct->TitleEvent.Title);
  526. }
  527. __finally
  528. {
  529. FreeCommStruct(CommStruct);
  530. }
  531. SendEvent(PrintTimeout);
  532. }
  533. //---------------------------------------------------------------------------
  534. void __fastcall TExternalConsole::WaitBeforeExit()
  535. {
  536. // noop
  537. }
  538. //---------------------------------------------------------------------------
  539. class TNullConsole : public TConsole
  540. {
  541. public:
  542. __fastcall TNullConsole();
  543. virtual void __fastcall Print(AnsiString Str, bool FromBeginning = false);
  544. virtual bool __fastcall Input(AnsiString & Str, bool Echo, unsigned int Timer);
  545. virtual int __fastcall Choice(AnsiString Options, int Cancel, int Break,
  546. int Timeouted, unsigned int Timer);
  547. virtual bool __fastcall PendingAbort();
  548. virtual void __fastcall SetTitle(AnsiString Title);
  549. virtual void __fastcall WaitBeforeExit();
  550. };
  551. //---------------------------------------------------------------------------
  552. __fastcall TNullConsole::TNullConsole()
  553. {
  554. }
  555. //---------------------------------------------------------------------------
  556. void __fastcall TNullConsole::Print(AnsiString /*Str*/, bool /*FromBeginning*/)
  557. {
  558. // noop
  559. }
  560. //---------------------------------------------------------------------------
  561. bool __fastcall TNullConsole::Input(AnsiString & /*Str*/, bool /*Echo*/,
  562. unsigned int /*Timer*/)
  563. {
  564. return false;
  565. }
  566. //---------------------------------------------------------------------------
  567. int __fastcall TNullConsole::Choice(AnsiString /*Options*/, int /*Cancel*/,
  568. int Break, int /*Timeouted*/, unsigned int /*Timer*/)
  569. {
  570. return Break;
  571. }
  572. //---------------------------------------------------------------------------
  573. bool __fastcall TNullConsole::PendingAbort()
  574. {
  575. return false;
  576. }
  577. //---------------------------------------------------------------------------
  578. void __fastcall TNullConsole::SetTitle(AnsiString /*Title*/)
  579. {
  580. // noop
  581. }
  582. //---------------------------------------------------------------------------
  583. void __fastcall TNullConsole::WaitBeforeExit()
  584. {
  585. assert(false);
  586. // noop
  587. }
  588. //---------------------------------------------------------------------------
  589. class TConsoleRunner
  590. {
  591. public:
  592. TConsoleRunner(TConsole * Console);
  593. int __fastcall Run(const AnsiString Session, TStrings * ScriptCommands);
  594. void __fastcall ShowException(Exception * E);
  595. protected:
  596. bool __fastcall Input(AnsiString & Str, bool Echo, unsigned int Timer);
  597. inline void __fastcall Print(const AnsiString & Str, bool FromBeginning = false);
  598. inline void __fastcall PrintLine(const AnsiString & Str);
  599. inline void __fastcall PrintMessage(const AnsiString & Str);
  600. void __fastcall UpdateTitle();
  601. inline void __fastcall NotifyAbort();
  602. inline bool __fastcall Aborted(bool AllowCompleteAbort = true);
  603. private:
  604. TManagementScript * FScript;
  605. TConsole * FConsole;
  606. TSynchronizeController FSynchronizeController;
  607. int FLastProgressLen;
  608. bool FSynchronizeAborted;
  609. bool FCommandError;
  610. bool FBatchScript;
  611. bool FAborted;
  612. void __fastcall ScriptPrint(TScript * Script, const AnsiString Str);
  613. void __fastcall ScriptPrintProgress(TScript * Script, bool First, const AnsiString Str);
  614. void __fastcall ScriptInput(TScript * Script, const AnsiString Prompt, AnsiString & Str);
  615. void __fastcall ScriptTerminalPromptUser(TTerminal * Terminal,
  616. AnsiString Prompt, TPromptKind Kind, AnsiString & Response, bool & Result, void * Arg);
  617. void __fastcall ScriptShowExtendedException(TTerminal * Terminal,
  618. Exception * E, void * Arg);
  619. void __fastcall ScriptTerminalQueryUser(TObject * Sender, const AnsiString Query,
  620. TStrings * MoreMessages, int Answers, const TQueryParams * Params, int & Answer,
  621. TQueryType QueryType, void * Arg);
  622. void __fastcall ScriptQueryCancel(TScript * Script, bool & Cancel);
  623. void __fastcall SynchronizeControllerAbort(TObject * Sender, bool Close);
  624. void __fastcall SynchronizeControllerLog(TSynchronizeController * Controller,
  625. TSynchronizeLogEntry Entry, const AnsiString Message);
  626. void __fastcall ScriptSynchronizeStartStop(TScript * Script,
  627. const AnsiString LocalDirectory, const AnsiString RemoteDirectory);
  628. void __fastcall SynchronizeControllerSynchronize(TSynchronizeController * Sender,
  629. const AnsiString LocalDirectory, const AnsiString RemoteDirectory,
  630. const TCopyParamType & CopyParam, const TSynchronizeParamType & Params,
  631. TSynchronizeChecklist ** Checklist, TSynchronizeOptions * Options, bool Full);
  632. void __fastcall SynchronizeControllerSynchronizeInvalid(TSynchronizeController * Sender,
  633. const AnsiString Directory, const AnsiString ErrorStr);
  634. void __fastcall SynchronizeControllerTooManyDirectories(TSynchronizeController * Sender,
  635. int & MaxDirectories);
  636. unsigned int InputTimeout();
  637. };
  638. //---------------------------------------------------------------------------
  639. TConsoleRunner::TConsoleRunner(TConsole * Console) :
  640. FSynchronizeController(&SynchronizeControllerSynchronize,
  641. &SynchronizeControllerSynchronizeInvalid,
  642. &SynchronizeControllerTooManyDirectories)
  643. {
  644. FConsole = Console;
  645. FLastProgressLen = 0;
  646. FScript = NULL;
  647. FAborted = false;
  648. FBatchScript = false;
  649. }
  650. //---------------------------------------------------------------------------
  651. unsigned int TConsoleRunner::InputTimeout()
  652. {
  653. return (FScript->Batch != TScript::BatchOff ? BATCH_INPUT_TIMEOUT : 0);
  654. }
  655. //---------------------------------------------------------------------------
  656. void __fastcall TConsoleRunner::ScriptInput(TScript * /*Script*/,
  657. const AnsiString Prompt, AnsiString & Str)
  658. {
  659. Print(Prompt);
  660. if (!Input(Str, true, InputTimeout()))
  661. {
  662. Abort();
  663. }
  664. }
  665. //---------------------------------------------------------------------------
  666. void __fastcall TConsoleRunner::Print(const AnsiString & Str, bool FromBeginning)
  667. {
  668. if (FLastProgressLen > 0)
  669. {
  670. FConsole->Print("\n" + Str, FromBeginning);
  671. FLastProgressLen = 0;
  672. }
  673. else
  674. {
  675. FConsole->Print(Str, FromBeginning);
  676. }
  677. }
  678. //---------------------------------------------------------------------------
  679. void __fastcall TConsoleRunner::PrintLine(const AnsiString & Str)
  680. {
  681. Print(Str + "\n");
  682. }
  683. //---------------------------------------------------------------------------
  684. void __fastcall TConsoleRunner::PrintMessage(const AnsiString & Str)
  685. {
  686. PrintLine(
  687. StringReplace(StringReplace(Str.TrimRight(), "\n\n", "\n", TReplaceFlags() << rfReplaceAll),
  688. "\n \n", "\n", TReplaceFlags() << rfReplaceAll));
  689. }
  690. //---------------------------------------------------------------------------
  691. void __fastcall TConsoleRunner::NotifyAbort()
  692. {
  693. if (FBatchScript)
  694. {
  695. FAborted = true;
  696. }
  697. }
  698. //---------------------------------------------------------------------------
  699. bool __fastcall TConsoleRunner::Aborted(bool AllowCompleteAbort)
  700. {
  701. bool Result;
  702. if (FAborted)
  703. {
  704. Result = true;
  705. }
  706. else
  707. {
  708. Result = FConsole->PendingAbort();
  709. if (Result)
  710. {
  711. PrintLine(LoadStr(USER_TERMINATED));
  712. if (AllowCompleteAbort)
  713. {
  714. NotifyAbort();
  715. }
  716. }
  717. }
  718. return Result;
  719. }
  720. //---------------------------------------------------------------------------
  721. void __fastcall TConsoleRunner::ScriptPrint(TScript * /*Script*/,
  722. const AnsiString Str)
  723. {
  724. Print(Str);
  725. }
  726. //---------------------------------------------------------------------------
  727. void __fastcall TConsoleRunner::ScriptPrintProgress(TScript * /*Script*/,
  728. bool First, const AnsiString Str)
  729. {
  730. AnsiString S = Str;
  731. if (First && (FLastProgressLen > 0))
  732. {
  733. S = "\n" + S;
  734. }
  735. else if (S.Length() < FLastProgressLen)
  736. {
  737. S += AnsiString::StringOfChar(' ', FLastProgressLen - S.Length());
  738. }
  739. FConsole->Print(S, true);
  740. FLastProgressLen = Str.Length();
  741. }
  742. //---------------------------------------------------------------------------
  743. void __fastcall TConsoleRunner::ScriptTerminalPromptUser(TTerminal * /*Terminal*/,
  744. AnsiString Prompt, TPromptKind Kind, AnsiString & Response, bool & Result,
  745. void * /*Arg*/)
  746. {
  747. AnsiString Caption = CutToChar(Prompt, '|', true);
  748. if (Prompt.IsEmpty())
  749. {
  750. Prompt = Caption;
  751. }
  752. if (!Prompt.IsEmpty() && (Prompt[Prompt.Length()] != ' '))
  753. {
  754. Prompt += ' ';
  755. }
  756. Print(Prompt);
  757. Result = Input(Response, (Kind == pkPrompt), InputTimeout());
  758. }
  759. //---------------------------------------------------------------------------
  760. void __fastcall TConsoleRunner::ScriptShowExtendedException(
  761. TTerminal * /*Terminal*/, Exception * E, void * /*Arg*/)
  762. {
  763. ShowException(E);
  764. }
  765. //---------------------------------------------------------------------------
  766. void __fastcall TConsoleRunner::ScriptTerminalQueryUser(TObject * /*Sender*/,
  767. const AnsiString Query, TStrings * MoreMessages, int Answers,
  768. const TQueryParams * Params, int & Answer, TQueryType /*QueryType*/,
  769. void * /*Arg*/)
  770. {
  771. AnsiString AQuery = Query;
  772. unsigned int Timer = 0;
  773. unsigned int Timeout = 0;
  774. int TimeoutA = 0;
  775. if (Params != NULL)
  776. {
  777. if (Params->Timeout > 0)
  778. {
  779. assert(Params->Timer == 0);
  780. Timeout = Params->Timeout;
  781. TimeoutA = Params->TimeoutAnswer;
  782. }
  783. if (Params->Timer > 0)
  784. {
  785. assert(Params->Timeout == 0);
  786. Timer = Params->Timer;
  787. if (Params->TimerAnswers > 0)
  788. {
  789. Answers = Params->TimerAnswers;
  790. }
  791. if (!Params->TimerMessage.IsEmpty())
  792. {
  793. AQuery = Params->TimerMessage;
  794. }
  795. }
  796. if (FLAGSET(Params->Params, qpFatalAbort))
  797. {
  798. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  799. }
  800. }
  801. int AAnswers = Answers;
  802. PrintMessage(AQuery);
  803. if ((MoreMessages != NULL) && (MoreMessages->Count > 0))
  804. {
  805. PrintMessage(MoreMessages->Text);
  806. }
  807. static const int MaxButtonCount = 15;
  808. int Buttons[MaxButtonCount];
  809. AnsiString Captions[MaxButtonCount];
  810. int ButtonCount = 0;
  811. #define ADD_BUTTON(TYPE, CAPTION) \
  812. if (FLAGSET(AAnswers, qa ## TYPE)) \
  813. { \
  814. assert(ButtonCount < MaxButtonCount); \
  815. Captions[ButtonCount] = CAPTION; \
  816. Buttons[ButtonCount] = qa ## TYPE; \
  817. ButtonCount++; \
  818. AAnswers -= qa ## TYPE; \
  819. }
  820. #define ADD_BUTTON_RES(TYPE) ADD_BUTTON(TYPE, LoadResourceString(&_SMsgDlg ## TYPE));
  821. ADD_BUTTON_RES(Yes);
  822. ADD_BUTTON_RES(No);
  823. ADD_BUTTON_RES(OK);
  824. ADD_BUTTON_RES(Cancel);
  825. ADD_BUTTON_RES(Abort);
  826. ADD_BUTTON_RES(Retry);
  827. ADD_BUTTON_RES(Ignore);
  828. // to keep the same order as for GUI message box
  829. ADD_BUTTON(Skip, LoadStr(SKIP_BUTTON));
  830. ADD_BUTTON_RES(All);
  831. ADD_BUTTON_RES(NoToAll);
  832. ADD_BUTTON_RES(YesToAll);
  833. ADD_BUTTON_RES(Help);
  834. #undef ADD_BUTTON_RES
  835. #undef ADD_BUTTON
  836. USEDPARAM(AAnswers);
  837. assert(AAnswers == 0);
  838. assert(ButtonCount > 0);
  839. if ((Params != NULL) && (Params->Aliases != NULL))
  840. {
  841. for (int bi = 0; bi < ButtonCount; bi++)
  842. {
  843. for (unsigned int ai = 0; ai < Params->AliasesCount; ai++)
  844. {
  845. if (static_cast<int>(Params->Aliases[ai].Button) == Buttons[bi])
  846. {
  847. Captions[bi] = Params->Aliases[ai].Alias;
  848. break;
  849. }
  850. }
  851. }
  852. }
  853. AnsiString Accels;
  854. for (int Index = 0; Index < ButtonCount; Index++)
  855. {
  856. AnsiString & Caption = Captions[Index];
  857. int P = Caption.Pos('&');
  858. if ((P > 0) && (P < Caption.Length()))
  859. {
  860. char Accel = AnsiUpperCase(Caption)[P + 1];
  861. if (Accels.Pos(Accel) > 0)
  862. {
  863. Caption.Delete(P, 1);
  864. Accels += ' ';
  865. }
  866. else
  867. {
  868. Accels += Accel;
  869. }
  870. }
  871. else
  872. {
  873. Accels += ' ';
  874. }
  875. }
  876. assert(Accels.Length() == ButtonCount);
  877. int NumberAccel = 0;
  878. int CancelA = CancelAnswer(Answers);
  879. int CancelIndex;
  880. int AbortA = AbortAnswer(Answers);
  881. int AbortIndex;
  882. int ContinueA = ContinueAnswer(Answers);
  883. int ContinueIndex;
  884. int TimeoutIndex = 0;
  885. for (int Index = 0; Index < ButtonCount; Index++)
  886. {
  887. AnsiString & Caption = Captions[Index];
  888. if (Accels[Index + 1] == ' ')
  889. {
  890. for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)
  891. {
  892. char C = AnsiUpperCase(Caption)[Index2];
  893. if ((C >= 'A') && (C <= 'Z') && (Accels.Pos(C) == 0))
  894. {
  895. Caption.Insert("&", Index2);
  896. Accels[Index + 1] = C;
  897. break;
  898. }
  899. }
  900. }
  901. if (Accels[Index + 1] == ' ')
  902. {
  903. for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)
  904. {
  905. char C = AnsiUpperCase(Caption)[Index2];
  906. if ((C != ' ') && (Accels.Pos(C) == 0))
  907. {
  908. Caption.Insert("&", Index2);
  909. Accels[Index + 1] = C;
  910. break;
  911. }
  912. }
  913. }
  914. if (Accels[Index + 1] == ' ')
  915. {
  916. NumberAccel++;
  917. assert(NumberAccel <= 9);
  918. Caption = FORMAT("&%d%s", (NumberAccel, Caption));
  919. Accels[Index + 1] = Caption[2];
  920. }
  921. if (Buttons[Index] == CancelA)
  922. {
  923. CancelIndex = Index + 1;
  924. }
  925. if (Buttons[Index] == AbortA)
  926. {
  927. AbortIndex = Index + 1;
  928. }
  929. if (Buttons[Index] == ContinueA)
  930. {
  931. ContinueIndex = Index + 1;
  932. }
  933. if (Buttons[Index] == ContinueA)
  934. {
  935. ContinueIndex = Index + 1;
  936. }
  937. if (Buttons[Index] == TimeoutA)
  938. {
  939. TimeoutIndex = Index + 1;
  940. }
  941. }
  942. assert(Accels.Pos(' ') == 0);
  943. bool Timeouting = (Timeout > 0);
  944. do
  945. {
  946. Answer = 0;
  947. int AnswerIndex;
  948. bool Retry;
  949. do
  950. {
  951. Retry = false;
  952. AnsiString Output;
  953. for (int i = 0; i < ButtonCount; i++)
  954. {
  955. if (i > 0)
  956. {
  957. Output += ", ";
  958. }
  959. AnsiString Caption = Captions[i];
  960. int P = Caption.Pos('&');
  961. assert(P >= 0);
  962. Caption[P] = '(';
  963. Caption.Insert(")", P + 2);
  964. if (i + 1 == TimeoutIndex)
  965. {
  966. assert(Timeouting);
  967. Caption = FMTLOAD(TIMEOUT_BUTTON, (Caption, int(Timeout / 1000)));
  968. }
  969. Output += Caption;
  970. }
  971. Output += ": ";
  972. // note that length of string may decrease over time due to number of
  973. // seconds length, but supposing it decreases by one character at time
  974. // at most, we do not mind as the prompt is terminated with space
  975. Print(Output, true);
  976. if (!Timeouting && (FScript->Batch == TScript::BatchContinue))
  977. {
  978. AnswerIndex = ContinueIndex;
  979. }
  980. else if (!Timeouting && (FScript->Batch != TScript::BatchOff))
  981. {
  982. AnswerIndex = AbortIndex;
  983. }
  984. else if (Timeouting && (Timeout < 1000))
  985. {
  986. AnswerIndex = TimeoutIndex;
  987. }
  988. else
  989. {
  990. AnswerIndex = FConsole->Choice(Accels, CancelIndex, -1, -2,
  991. (Timeouting ? 1000 : Timer));
  992. if (AnswerIndex == -1)
  993. {
  994. NotifyAbort();
  995. AnswerIndex = AbortIndex;
  996. }
  997. else if (AnswerIndex == -2)
  998. {
  999. if (Timeouting)
  1000. {
  1001. assert(Timeout >= 1000);
  1002. Timeout -= 1000;
  1003. Retry = true;
  1004. }
  1005. else
  1006. {
  1007. assert((Params != NULL) && (Params->TimerEvent != NULL));
  1008. if ((Params != NULL) && (Params->TimerEvent != NULL))
  1009. {
  1010. unsigned int AAnswer = 0;
  1011. Params->TimerEvent(AAnswer);
  1012. if (AAnswer != 0)
  1013. {
  1014. Answer = AAnswer;
  1015. }
  1016. else
  1017. {
  1018. Retry = true;
  1019. }
  1020. }
  1021. }
  1022. }
  1023. }
  1024. }
  1025. while (Retry);
  1026. if (Answer == 0)
  1027. {
  1028. assert((AnswerIndex >= 1) && (AnswerIndex <= Accels.Length()));
  1029. AnsiString AnswerCaption = Captions[AnswerIndex - 1];
  1030. int P = AnswerCaption.Pos("&");
  1031. assert(P >= 0);
  1032. AnswerCaption.Delete(P, 1);
  1033. PrintLine(AnswerCaption);
  1034. Answer = Buttons[AnswerIndex - 1];
  1035. }
  1036. else
  1037. {
  1038. PrintLine("");
  1039. }
  1040. }
  1041. while (Answer == 0);
  1042. if (Answer == qaAbort)
  1043. {
  1044. FCommandError = true;
  1045. }
  1046. }
  1047. //---------------------------------------------------------------------------
  1048. void __fastcall TConsoleRunner::ScriptQueryCancel(TScript * /*Script*/, bool & Cancel)
  1049. {
  1050. if (Aborted())
  1051. {
  1052. Cancel = true;
  1053. }
  1054. }
  1055. //---------------------------------------------------------------------------
  1056. void __fastcall TConsoleRunner::ScriptSynchronizeStartStop(TScript * /*Script*/,
  1057. const AnsiString LocalDirectory, const AnsiString RemoteDirectory)
  1058. {
  1059. TSynchronizeParamType Params;
  1060. Params.LocalDirectory = LocalDirectory;
  1061. Params.RemoteDirectory = RemoteDirectory;
  1062. Params.Params = -1; // never used
  1063. Params.Options = soRecurse;
  1064. FSynchronizeController.StartStop(Application, true, Params,
  1065. FScript->CopyParam, NULL, SynchronizeControllerAbort, NULL,
  1066. SynchronizeControllerLog);
  1067. try
  1068. {
  1069. FSynchronizeAborted = false;
  1070. while (!FSynchronizeAborted && !Aborted(false))
  1071. {
  1072. Application->HandleMessage();
  1073. }
  1074. }
  1075. __finally
  1076. {
  1077. FSynchronizeController.StartStop(Application, false, Params,
  1078. FScript->CopyParam, NULL, SynchronizeControllerAbort, NULL,
  1079. SynchronizeControllerLog);
  1080. }
  1081. }
  1082. //---------------------------------------------------------------------------
  1083. void __fastcall TConsoleRunner::SynchronizeControllerLog(
  1084. TSynchronizeController * /*Controller*/, TSynchronizeLogEntry /*Entry*/,
  1085. const AnsiString Message)
  1086. {
  1087. PrintLine(Message);
  1088. }
  1089. //---------------------------------------------------------------------------
  1090. void __fastcall TConsoleRunner::SynchronizeControllerAbort(TObject * /*Sender*/,
  1091. bool /*Close*/)
  1092. {
  1093. FSynchronizeAborted = true;
  1094. }
  1095. //---------------------------------------------------------------------------
  1096. void __fastcall TConsoleRunner::SynchronizeControllerSynchronize(
  1097. TSynchronizeController * /*Sender*/, const AnsiString LocalDirectory,
  1098. const AnsiString RemoteDirectory, const TCopyParamType & CopyParam,
  1099. const TSynchronizeParamType & /*Params*/, TSynchronizeChecklist ** Checklist,
  1100. TSynchronizeOptions * /*Options*/, bool Full)
  1101. {
  1102. if (!Full)
  1103. {
  1104. FScript->Synchronize(LocalDirectory, RemoteDirectory, CopyParam, Checklist);
  1105. }
  1106. }
  1107. //---------------------------------------------------------------------------
  1108. void __fastcall TConsoleRunner::SynchronizeControllerSynchronizeInvalid(
  1109. TSynchronizeController * /*Sender*/, const AnsiString Directory, const AnsiString ErrorStr)
  1110. {
  1111. if (!Directory.IsEmpty())
  1112. {
  1113. PrintLine(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)));
  1114. }
  1115. else
  1116. {
  1117. PrintLine(LoadStr(WATCH_ERROR_GENERAL));
  1118. }
  1119. if (!ErrorStr.IsEmpty())
  1120. {
  1121. PrintLine(ErrorStr);
  1122. }
  1123. }
  1124. //---------------------------------------------------------------------------
  1125. void __fastcall TConsoleRunner::SynchronizeControllerTooManyDirectories(
  1126. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  1127. {
  1128. if (Aborted())
  1129. {
  1130. Abort();
  1131. }
  1132. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  1133. {
  1134. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  1135. }
  1136. else
  1137. {
  1138. MaxDirectories *= 2;
  1139. }
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. void __fastcall TConsoleRunner::ShowException(Exception * E)
  1143. {
  1144. if (!E->Message.IsEmpty() &&
  1145. (dynamic_cast<EAbort *>(E) == NULL))
  1146. {
  1147. FCommandError = true;
  1148. PrintMessage(TranslateExceptionMessage(E));
  1149. ExtException * EE = dynamic_cast<ExtException *>(E);
  1150. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1151. {
  1152. PrintMessage(EE->MoreMessages->Text);
  1153. }
  1154. }
  1155. }
  1156. //---------------------------------------------------------------------------
  1157. bool __fastcall TConsoleRunner::Input(AnsiString & Str, bool Echo, unsigned int Timeout)
  1158. {
  1159. bool Result = FConsole->Input(Str, Echo, Timeout);
  1160. if (Result)
  1161. {
  1162. while (!Str.IsEmpty() &&
  1163. ((Str[Str.Length()] == '\n') || (Str[Str.Length()] == '\r')))
  1164. {
  1165. Str.SetLength(Str.Length() - 1);
  1166. }
  1167. }
  1168. else
  1169. {
  1170. NotifyAbort();
  1171. }
  1172. return Result;
  1173. }
  1174. //---------------------------------------------------------------------------
  1175. int __fastcall TConsoleRunner::Run(const AnsiString Session, TStrings * ScriptCommands)
  1176. {
  1177. bool AnyError = false;
  1178. try
  1179. {
  1180. FScript = new TManagementScript(StoredSessions);
  1181. try
  1182. {
  1183. FScript->CopyParam = GUIConfiguration->DefaultCopyParam;
  1184. FScript->SynchronizeParams = GUIConfiguration->SynchronizeParams;
  1185. FScript->OnPrint = ScriptPrint;
  1186. FScript->OnPrintProgress = ScriptPrintProgress;
  1187. FScript->OnInput = ScriptInput;
  1188. FScript->OnTerminalPromptUser = ScriptTerminalPromptUser;
  1189. FScript->OnShowExtendedException = ScriptShowExtendedException;
  1190. FScript->OnTerminalQueryUser = ScriptTerminalQueryUser;
  1191. FScript->OnQueryCancel = ScriptQueryCancel;
  1192. FScript->OnSynchronizeStartStop = ScriptSynchronizeStartStop;
  1193. UpdateTitle();
  1194. // everything until the first manually entered command is "batch"
  1195. // (including opening session from command line and script file)
  1196. FBatchScript = true;
  1197. if (!Session.IsEmpty())
  1198. {
  1199. FScript->Connect(Session);
  1200. }
  1201. int ScriptPos = 0;
  1202. bool Result;
  1203. do
  1204. {
  1205. UpdateTitle();
  1206. AnsiString Command;
  1207. if ((ScriptCommands != NULL) && (ScriptPos < ScriptCommands->Count))
  1208. {
  1209. Result = true;
  1210. Command = ScriptCommands->Strings[ScriptPos];
  1211. ScriptPos++;
  1212. }
  1213. else
  1214. {
  1215. // no longer batch
  1216. FBatchScript = false;
  1217. Print("winscp> ");
  1218. Result = Input(Command, true, 0);
  1219. }
  1220. if (Result)
  1221. {
  1222. FCommandError = false;
  1223. FScript->Command(Command);
  1224. if (FCommandError)
  1225. {
  1226. AnyError = true;
  1227. if (FScript->Batch == TScript::BatchAbort)
  1228. {
  1229. Result = false;
  1230. }
  1231. }
  1232. }
  1233. }
  1234. while (Result && FScript->Continue && !Aborted());
  1235. }
  1236. __finally
  1237. {
  1238. delete FScript;
  1239. FScript = NULL;
  1240. }
  1241. }
  1242. catch(Exception & E)
  1243. {
  1244. ShowException(&E);
  1245. AnyError = true;
  1246. }
  1247. return AnyError ? RESULT_ANY_ERROR : RESULT_SUCCESS;
  1248. }
  1249. //---------------------------------------------------------------------------
  1250. void __fastcall TConsoleRunner::UpdateTitle()
  1251. {
  1252. AnsiString NewTitle;
  1253. if (FScript->Terminal != NULL)
  1254. {
  1255. NewTitle = FMTLOAD(APP_CAPTION, (FScript->Terminal->SessionData->SessionName, AppName));
  1256. }
  1257. else
  1258. {
  1259. NewTitle = AppName;
  1260. }
  1261. FConsole->SetTitle(NewTitle);
  1262. }
  1263. //---------------------------------------------------------------------------
  1264. void __fastcall LoadScriptFromFile(AnsiString FileName, TStrings * Lines)
  1265. {
  1266. AnsiString UTFBOM = "\xEF\xBB\xBF";
  1267. Lines->LoadFromFile(FileName);
  1268. if ((Lines->Count > 0) &&
  1269. (Lines->Strings[0].SubString(1, UTFBOM.Length()) == UTFBOM))
  1270. {
  1271. Lines->Strings[0] = Lines->Strings[0].SubString(
  1272. UTFBOM.Length() + 1, Lines->Strings[0].Length() - UTFBOM.Length());
  1273. for (int Index = 0; Index < Lines->Count; Index++)
  1274. {
  1275. Lines->Strings[Index] = DecodeUTF(Lines->Strings[Index]);
  1276. }
  1277. }
  1278. }
  1279. //---------------------------------------------------------------------------
  1280. int __fastcall Console(bool Help)
  1281. {
  1282. TProgramParams * Params = TProgramParams::Instance();
  1283. int Result = 0;
  1284. TConsole * Console = NULL;
  1285. TConsoleRunner * Runner = NULL;
  1286. TStrings * ScriptCommands = new TStringList();
  1287. try
  1288. {
  1289. AnsiString ConsoleInstance;
  1290. if (Params->FindSwitch("consoleinstance", ConsoleInstance))
  1291. {
  1292. Console = new TExternalConsole(ConsoleInstance);
  1293. }
  1294. else if (Params->FindSwitch("Console") || Help)
  1295. {
  1296. Console = TOwnConsole::Instance();
  1297. }
  1298. else
  1299. {
  1300. Console = new TNullConsole();
  1301. }
  1302. if (Help)
  1303. {
  1304. AnsiString Usage = LoadStr(USAGE3, 10240);
  1305. AnsiString ExeBaseName = ChangeFileExt(ExtractFileName(Application->ExeName), "");
  1306. Usage = StringReplace(Usage, "%APP%", ExeBaseName,
  1307. TReplaceFlags() << rfReplaceAll << rfIgnoreCase);
  1308. AnsiString Copyright = StringReplace(LoadStr(WINSCP_COPYRIGHT), "©", "(c)",
  1309. TReplaceFlags() << rfReplaceAll << rfIgnoreCase);
  1310. Usage = FORMAT(Usage, (Configuration->VersionStr, Copyright));
  1311. Console->Print(Usage);
  1312. Console->WaitBeforeExit();
  1313. }
  1314. else
  1315. {
  1316. Runner = new TConsoleRunner(Console);
  1317. try
  1318. {
  1319. AnsiString Value;
  1320. if (Params->FindSwitch("script", Value) && !Value.IsEmpty())
  1321. {
  1322. LoadScriptFromFile(Value, ScriptCommands);
  1323. }
  1324. Params->FindSwitch("command", ScriptCommands);
  1325. bool Url = false;
  1326. AnsiString Session;
  1327. if (Params->ParamCount >= 1)
  1328. {
  1329. Session = Params->Param[1];
  1330. }
  1331. bool DefaultsOnly;
  1332. delete StoredSessions->ParseUrl(Session, DefaultsOnly,
  1333. puDecodeUrlChars, NULL, &Url);
  1334. if (Url || Params->FindSwitch("Unsafe"))
  1335. {
  1336. // prevent any automatic action when URL is provided on
  1337. // command-line (the check is duplicated in Execute())
  1338. ScriptCommands->Clear();
  1339. }
  1340. else
  1341. {
  1342. AnsiString LogFile;
  1343. if (Params->FindSwitch("Log", LogFile))
  1344. {
  1345. Configuration->TemporaryLogging(LogFile);
  1346. }
  1347. }
  1348. Result = Runner->Run(Session,
  1349. (ScriptCommands->Count > 0 ? ScriptCommands : NULL));
  1350. }
  1351. catch(Exception & E)
  1352. {
  1353. Runner->ShowException(&E);
  1354. Result = RESULT_ANY_ERROR;
  1355. }
  1356. }
  1357. }
  1358. __finally
  1359. {
  1360. delete Runner;
  1361. delete Console;
  1362. delete ScriptCommands;
  1363. }
  1364. return Result;
  1365. }