ConsoleRunner.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  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);
  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)
  667. {
  668. if (FLastProgressLen > 0)
  669. {
  670. FConsole->Print("\n" + Str);
  671. FLastProgressLen = 0;
  672. }
  673. else
  674. {
  675. FConsole->Print(Str);
  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. if (!Prompt.IsEmpty() && (Prompt[Prompt.Length()] != ' '))
  748. {
  749. Prompt += ' ';
  750. }
  751. Print(Prompt);
  752. Result = Input(Response, (Kind == pkPrompt), InputTimeout());
  753. }
  754. //---------------------------------------------------------------------------
  755. void __fastcall TConsoleRunner::ScriptShowExtendedException(
  756. TTerminal * /*Terminal*/, Exception * E, void * /*Arg*/)
  757. {
  758. ShowException(E);
  759. }
  760. //---------------------------------------------------------------------------
  761. void __fastcall TConsoleRunner::ScriptTerminalQueryUser(TObject * /*Sender*/,
  762. const AnsiString Query, TStrings * MoreMessages, int Answers,
  763. const TQueryParams * Params, int & Answer, TQueryType /*QueryType*/,
  764. void * /*Arg*/)
  765. {
  766. AnsiString AQuery = Query;
  767. unsigned int Timer = 0;
  768. Answer = 0;
  769. if (Params != NULL)
  770. {
  771. if (Params->Timer > 0)
  772. {
  773. Timer = Params->Timer;
  774. if (Params->TimerAnswers > 0)
  775. {
  776. Answers = Params->TimerAnswers;
  777. }
  778. if (!Params->TimerMessage.IsEmpty())
  779. {
  780. AQuery = Params->TimerMessage;
  781. }
  782. }
  783. if (FLAGSET(Params->Params, qpFatalAbort))
  784. {
  785. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  786. }
  787. }
  788. int AAnswers = Answers;
  789. PrintMessage(AQuery);
  790. if ((MoreMessages != NULL) && (MoreMessages->Count > 0))
  791. {
  792. PrintMessage(MoreMessages->Text);
  793. }
  794. static const int MaxButtonCount = 15;
  795. int Buttons[MaxButtonCount];
  796. AnsiString Captions[MaxButtonCount];
  797. int ButtonCount = 0;
  798. #define ADD_BUTTON(TYPE, CAPTION) \
  799. if (FLAGSET(AAnswers, qa ## TYPE)) \
  800. { \
  801. assert(ButtonCount < MaxButtonCount); \
  802. Captions[ButtonCount] = CAPTION; \
  803. Buttons[ButtonCount] = qa ## TYPE; \
  804. ButtonCount++; \
  805. AAnswers -= qa ## TYPE; \
  806. }
  807. #define ADD_BUTTON_RES(TYPE) ADD_BUTTON(TYPE, LoadResourceString(&_SMsgDlg ## TYPE));
  808. ADD_BUTTON_RES(Yes);
  809. ADD_BUTTON_RES(No);
  810. ADD_BUTTON_RES(OK);
  811. ADD_BUTTON_RES(Cancel);
  812. ADD_BUTTON_RES(Abort);
  813. ADD_BUTTON_RES(Retry);
  814. ADD_BUTTON_RES(Ignore);
  815. // to keep the same order as for GUI message box
  816. ADD_BUTTON(Skip, LoadStr(SKIP_BUTTON));
  817. ADD_BUTTON_RES(All);
  818. ADD_BUTTON_RES(NoToAll);
  819. ADD_BUTTON_RES(YesToAll);
  820. ADD_BUTTON_RES(Help);
  821. #undef ADD_BUTTON_RES
  822. #undef ADD_BUTTON
  823. USEDPARAM(AAnswers);
  824. assert(AAnswers == 0);
  825. assert(ButtonCount > 0);
  826. if ((Params != NULL) && (Params->Aliases != NULL))
  827. {
  828. for (int bi = 0; bi < ButtonCount; bi++)
  829. {
  830. for (unsigned int ai = 0; ai < Params->AliasesCount; ai++)
  831. {
  832. if (static_cast<int>(Params->Aliases[ai].Button) == Buttons[bi])
  833. {
  834. Captions[bi] = Params->Aliases[ai].Alias;
  835. break;
  836. }
  837. }
  838. }
  839. }
  840. AnsiString Accels;
  841. for (int Index = 0; Index < ButtonCount; Index++)
  842. {
  843. AnsiString & Caption = Captions[Index];
  844. int P = Caption.Pos('&');
  845. if ((P > 0) && (P < Caption.Length()))
  846. {
  847. char Accel = AnsiUpperCase(Caption)[P + 1];
  848. if (Accels.Pos(Accel) > 0)
  849. {
  850. Caption.Delete(P, 1);
  851. Accels += ' ';
  852. }
  853. else
  854. {
  855. Accels += Accel;
  856. }
  857. }
  858. else
  859. {
  860. Accels += ' ';
  861. }
  862. }
  863. assert(Accels.Length() == ButtonCount);
  864. int NumberAccel = 0;
  865. int CancelA = CancelAnswer(Answers);
  866. int CancelIndex;
  867. int AbortA = AbortAnswer(Answers);
  868. int AbortIndex;
  869. int ContinueA = ContinueAnswer(Answers);
  870. int ContinueIndex;
  871. for (int Index = 0; Index < ButtonCount; Index++)
  872. {
  873. AnsiString & Caption = Captions[Index];
  874. if (Accels[Index + 1] == ' ')
  875. {
  876. for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)
  877. {
  878. char C = AnsiUpperCase(Caption)[Index2];
  879. if ((C >= 'A') && (C <= 'Z') && (Accels.Pos(C) == 0))
  880. {
  881. Caption.Insert("&", Index2);
  882. Accels[Index + 1] = C;
  883. break;
  884. }
  885. }
  886. }
  887. if (Accels[Index + 1] == ' ')
  888. {
  889. for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)
  890. {
  891. char C = AnsiUpperCase(Caption)[Index2];
  892. if ((C != ' ') && (Accels.Pos(C) == 0))
  893. {
  894. Caption.Insert("&", Index2);
  895. Accels[Index + 1] = C;
  896. break;
  897. }
  898. }
  899. }
  900. if (Accels[Index + 1] == ' ')
  901. {
  902. NumberAccel++;
  903. assert(NumberAccel <= 9);
  904. Caption = FORMAT("&%d%s", (NumberAccel, Caption));
  905. Accels[Index + 1] = Caption[2];
  906. }
  907. if (Buttons[Index] == CancelA)
  908. {
  909. CancelIndex = Index + 1;
  910. }
  911. if (Buttons[Index] == AbortA)
  912. {
  913. AbortIndex = Index + 1;
  914. }
  915. if (Buttons[Index] == ContinueA)
  916. {
  917. ContinueIndex = Index + 1;
  918. }
  919. }
  920. assert(Accels.Pos(' ') == 0);
  921. AnsiString Output;
  922. for (int i = 0; i < ButtonCount; i++)
  923. {
  924. if (i > 0)
  925. {
  926. Output += ", ";
  927. }
  928. AnsiString Caption = Captions[i];
  929. int P = Caption.Pos('&');
  930. assert(P >= 0);
  931. Caption[P] = '(';
  932. Caption.Insert(")", P + 2);
  933. Output += Caption;
  934. }
  935. Output += ": ";
  936. Print(Output);
  937. int AnswerIndex;
  938. if (FScript->Batch == TScript::BatchContinue)
  939. {
  940. AnswerIndex = ContinueIndex;
  941. }
  942. else if (FScript->Batch != TScript::BatchOff)
  943. {
  944. AnswerIndex = AbortIndex;
  945. }
  946. else
  947. {
  948. bool Retry;
  949. do
  950. {
  951. Retry = false;
  952. AnswerIndex = FConsole->Choice(Accels, CancelIndex, -1, -2, Timer);
  953. if (AnswerIndex == -1)
  954. {
  955. NotifyAbort();
  956. AnswerIndex = AbortIndex;
  957. }
  958. else if (AnswerIndex == -2)
  959. {
  960. assert((Params != NULL) && (Params->TimerEvent != NULL));
  961. if ((Params != NULL) && (Params->TimerEvent != NULL))
  962. {
  963. unsigned int AAnswer = 0;
  964. Params->TimerEvent(AAnswer);
  965. if (AAnswer != 0)
  966. {
  967. Answer = AAnswer;
  968. }
  969. else
  970. {
  971. Retry = true;
  972. }
  973. }
  974. }
  975. }
  976. while (Retry);
  977. }
  978. if (Answer == 0)
  979. {
  980. assert((AnswerIndex >= 1) && (AnswerIndex <= Accels.Length()));
  981. AnsiString AnswerCaption = Captions[AnswerIndex - 1];
  982. int P = AnswerCaption.Pos("&");
  983. assert(P >= 0);
  984. AnswerCaption.Delete(P, 1);
  985. PrintLine(AnswerCaption);
  986. Answer = Buttons[AnswerIndex - 1];
  987. }
  988. else
  989. {
  990. PrintLine("");
  991. }
  992. if (Answer == qaAbort)
  993. {
  994. FCommandError = true;
  995. }
  996. }
  997. //---------------------------------------------------------------------------
  998. void __fastcall TConsoleRunner::ScriptQueryCancel(TScript * /*Script*/, bool & Cancel)
  999. {
  1000. if (Aborted())
  1001. {
  1002. Cancel = true;
  1003. }
  1004. }
  1005. //---------------------------------------------------------------------------
  1006. void __fastcall TConsoleRunner::ScriptSynchronizeStartStop(TScript * /*Script*/,
  1007. const AnsiString LocalDirectory, const AnsiString RemoteDirectory)
  1008. {
  1009. TSynchronizeParamType Params;
  1010. Params.LocalDirectory = LocalDirectory;
  1011. Params.RemoteDirectory = RemoteDirectory;
  1012. Params.Params = -1; // never used
  1013. Params.Options = soRecurse;
  1014. FSynchronizeController.StartStop(Application, true, Params,
  1015. FScript->CopyParam, NULL, SynchronizeControllerAbort, NULL,
  1016. SynchronizeControllerLog);
  1017. try
  1018. {
  1019. FSynchronizeAborted = false;
  1020. while (!FSynchronizeAborted && !Aborted(false))
  1021. {
  1022. Application->HandleMessage();
  1023. }
  1024. }
  1025. __finally
  1026. {
  1027. FSynchronizeController.StartStop(Application, false, Params,
  1028. FScript->CopyParam, NULL, SynchronizeControllerAbort, NULL,
  1029. SynchronizeControllerLog);
  1030. }
  1031. }
  1032. //---------------------------------------------------------------------------
  1033. void __fastcall TConsoleRunner::SynchronizeControllerLog(
  1034. TSynchronizeController * /*Controller*/, TSynchronizeLogEntry /*Entry*/,
  1035. const AnsiString Message)
  1036. {
  1037. PrintLine(Message);
  1038. }
  1039. //---------------------------------------------------------------------------
  1040. void __fastcall TConsoleRunner::SynchronizeControllerAbort(TObject * /*Sender*/,
  1041. bool /*Close*/)
  1042. {
  1043. FSynchronizeAborted = true;
  1044. }
  1045. //---------------------------------------------------------------------------
  1046. void __fastcall TConsoleRunner::SynchronizeControllerSynchronize(
  1047. TSynchronizeController * /*Sender*/, const AnsiString LocalDirectory,
  1048. const AnsiString RemoteDirectory, const TCopyParamType & CopyParam,
  1049. const TSynchronizeParamType & /*Params*/, TSynchronizeChecklist ** Checklist,
  1050. TSynchronizeOptions * /*Options*/, bool Full)
  1051. {
  1052. if (!Full)
  1053. {
  1054. FScript->Synchronize(LocalDirectory, RemoteDirectory, CopyParam, Checklist);
  1055. }
  1056. }
  1057. //---------------------------------------------------------------------------
  1058. void __fastcall TConsoleRunner::SynchronizeControllerSynchronizeInvalid(
  1059. TSynchronizeController * /*Sender*/, const AnsiString Directory, const AnsiString ErrorStr)
  1060. {
  1061. if (!Directory.IsEmpty())
  1062. {
  1063. PrintLine(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)));
  1064. }
  1065. else
  1066. {
  1067. PrintLine(LoadStr(WATCH_ERROR_GENERAL));
  1068. }
  1069. if (!ErrorStr.IsEmpty())
  1070. {
  1071. PrintLine(ErrorStr);
  1072. }
  1073. }
  1074. //---------------------------------------------------------------------------
  1075. void __fastcall TConsoleRunner::SynchronizeControllerTooManyDirectories(
  1076. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  1077. {
  1078. if (Aborted())
  1079. {
  1080. Abort();
  1081. }
  1082. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  1083. {
  1084. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  1085. }
  1086. else
  1087. {
  1088. MaxDirectories *= 2;
  1089. }
  1090. }
  1091. //---------------------------------------------------------------------------
  1092. void __fastcall TConsoleRunner::ShowException(Exception * E)
  1093. {
  1094. if (!E->Message.IsEmpty() &&
  1095. (dynamic_cast<EAbort *>(E) == NULL))
  1096. {
  1097. FCommandError = true;
  1098. PrintMessage(TranslateExceptionMessage(E));
  1099. ExtException * EE = dynamic_cast<ExtException *>(E);
  1100. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1101. {
  1102. PrintMessage(EE->MoreMessages->Text);
  1103. }
  1104. }
  1105. }
  1106. //---------------------------------------------------------------------------
  1107. bool __fastcall TConsoleRunner::Input(AnsiString & Str, bool Echo, unsigned int Timeout)
  1108. {
  1109. bool Result = FConsole->Input(Str, Echo, Timeout);
  1110. if (Result)
  1111. {
  1112. while (!Str.IsEmpty() &&
  1113. ((Str[Str.Length()] == '\n') || (Str[Str.Length()] == '\r')))
  1114. {
  1115. Str.SetLength(Str.Length() - 1);
  1116. }
  1117. }
  1118. else
  1119. {
  1120. NotifyAbort();
  1121. }
  1122. return Result;
  1123. }
  1124. //---------------------------------------------------------------------------
  1125. int __fastcall TConsoleRunner::Run(const AnsiString Session, TStrings * ScriptCommands)
  1126. {
  1127. bool AnyError = false;
  1128. try
  1129. {
  1130. FScript = new TManagementScript(StoredSessions);
  1131. try
  1132. {
  1133. FScript->CopyParam = GUIConfiguration->DefaultCopyParam;
  1134. FScript->SynchronizeParams = GUIConfiguration->SynchronizeParams;
  1135. FScript->OnPrint = ScriptPrint;
  1136. FScript->OnPrintProgress = ScriptPrintProgress;
  1137. FScript->OnInput = ScriptInput;
  1138. FScript->OnTerminalPromptUser = ScriptTerminalPromptUser;
  1139. FScript->OnShowExtendedException = ScriptShowExtendedException;
  1140. FScript->OnTerminalQueryUser = ScriptTerminalQueryUser;
  1141. FScript->OnQueryCancel = ScriptQueryCancel;
  1142. FScript->OnSynchronizeStartStop = ScriptSynchronizeStartStop;
  1143. UpdateTitle();
  1144. // everything until the first manually entered command is "batch"
  1145. // (including opening session from command line and script file)
  1146. FBatchScript = true;
  1147. if (!Session.IsEmpty())
  1148. {
  1149. FScript->Connect(Session);
  1150. }
  1151. int ScriptPos = 0;
  1152. bool Result;
  1153. do
  1154. {
  1155. UpdateTitle();
  1156. AnsiString Command;
  1157. if ((ScriptCommands != NULL) && (ScriptPos < ScriptCommands->Count))
  1158. {
  1159. Result = true;
  1160. Command = ScriptCommands->Strings[ScriptPos];
  1161. ScriptPos++;
  1162. }
  1163. else
  1164. {
  1165. // no longer batch
  1166. FBatchScript = false;
  1167. Print("winscp> ");
  1168. Result = Input(Command, true, 0);
  1169. }
  1170. if (Result)
  1171. {
  1172. FCommandError = false;
  1173. FScript->Command(Command);
  1174. if (FCommandError)
  1175. {
  1176. AnyError = true;
  1177. if (FScript->Batch == TScript::BatchAbort)
  1178. {
  1179. Result = false;
  1180. }
  1181. }
  1182. }
  1183. }
  1184. while (Result && FScript->Continue && !Aborted());
  1185. }
  1186. __finally
  1187. {
  1188. delete FScript;
  1189. FScript = NULL;
  1190. }
  1191. }
  1192. catch(Exception & E)
  1193. {
  1194. ShowException(&E);
  1195. AnyError = true;
  1196. }
  1197. return AnyError ? RESULT_ANY_ERROR : RESULT_SUCCESS;
  1198. }
  1199. //---------------------------------------------------------------------------
  1200. void __fastcall TConsoleRunner::UpdateTitle()
  1201. {
  1202. AnsiString NewTitle;
  1203. if (FScript->Terminal != NULL)
  1204. {
  1205. NewTitle = FMTLOAD(APP_CAPTION, (FScript->Terminal->SessionData->SessionName, AppName));
  1206. }
  1207. else
  1208. {
  1209. NewTitle = AppName;
  1210. }
  1211. FConsole->SetTitle(NewTitle);
  1212. }
  1213. //---------------------------------------------------------------------------
  1214. void __fastcall LoadScriptFromFile(AnsiString FileName, TStrings * Lines)
  1215. {
  1216. AnsiString UTFBOM = "\xEF\xBB\xBF";
  1217. Lines->LoadFromFile(FileName);
  1218. if ((Lines->Count > 0) &&
  1219. (Lines->Strings[0].SubString(1, UTFBOM.Length()) == UTFBOM))
  1220. {
  1221. Lines->Strings[0] = Lines->Strings[0].SubString(
  1222. UTFBOM.Length() + 1, Lines->Strings[0].Length() - UTFBOM.Length());
  1223. for (int Index = 0; Index < Lines->Count; Index++)
  1224. {
  1225. Lines->Strings[Index] = DecodeUTF(Lines->Strings[Index]);
  1226. }
  1227. }
  1228. }
  1229. //---------------------------------------------------------------------------
  1230. int __fastcall Console(bool Help)
  1231. {
  1232. TProgramParams * Params = TProgramParams::Instance();
  1233. int Result = 0;
  1234. TConsole * Console = NULL;
  1235. TConsoleRunner * Runner = NULL;
  1236. TStrings * ScriptCommands = new TStringList();
  1237. try
  1238. {
  1239. AnsiString ConsoleInstance;
  1240. if (Params->FindSwitch("consoleinstance", ConsoleInstance))
  1241. {
  1242. Console = new TExternalConsole(ConsoleInstance);
  1243. }
  1244. else if (Params->FindSwitch("Console") || Help)
  1245. {
  1246. Console = TOwnConsole::Instance();
  1247. }
  1248. else
  1249. {
  1250. Console = new TNullConsole();
  1251. }
  1252. if (Help)
  1253. {
  1254. AnsiString Usage = LoadStr(USAGE3, 10240);
  1255. AnsiString ExeBaseName = ChangeFileExt(ExtractFileName(Application->ExeName), "");
  1256. Usage = StringReplace(Usage, "%APP%", ExeBaseName,
  1257. TReplaceFlags() << rfReplaceAll << rfIgnoreCase);
  1258. AnsiString Copyright = StringReplace(LoadStr(WINSCP_COPYRIGHT), "©", "(c)",
  1259. TReplaceFlags() << rfReplaceAll << rfIgnoreCase);
  1260. Usage = FORMAT(Usage, (Configuration->VersionStr, Copyright));
  1261. Console->Print(Usage);
  1262. Console->WaitBeforeExit();
  1263. }
  1264. else
  1265. {
  1266. Runner = new TConsoleRunner(Console);
  1267. try
  1268. {
  1269. AnsiString Value;
  1270. if (Params->FindSwitch("script", Value) && !Value.IsEmpty())
  1271. {
  1272. LoadScriptFromFile(Value, ScriptCommands);
  1273. }
  1274. Params->FindSwitch("command", ScriptCommands);
  1275. bool Url = false;
  1276. AnsiString Session;
  1277. if (Params->ParamCount >= 1)
  1278. {
  1279. Session = Params->Param[1];
  1280. }
  1281. bool DefaultsOnly;
  1282. delete StoredSessions->ParseUrl(Session, DefaultsOnly,
  1283. puDecodeUrlChars, NULL, &Url);
  1284. if (Url)
  1285. {
  1286. // prevent any automatic action when URL is provided on
  1287. // command-line
  1288. ScriptCommands->Clear();
  1289. }
  1290. else
  1291. {
  1292. AnsiString LogFile;
  1293. if (Params->FindSwitch("Log", LogFile))
  1294. {
  1295. Configuration->TemporaryLogging(LogFile);
  1296. }
  1297. }
  1298. Result = Runner->Run(Session,
  1299. (ScriptCommands->Count > 0 ? ScriptCommands : NULL));
  1300. }
  1301. catch(Exception & E)
  1302. {
  1303. Runner->ShowException(&E);
  1304. Result = RESULT_ANY_ERROR;
  1305. }
  1306. }
  1307. }
  1308. __finally
  1309. {
  1310. delete Runner;
  1311. delete Console;
  1312. delete ScriptCommands;
  1313. }
  1314. return Result;
  1315. }