TerminalManager.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include "TerminalManager.h"
  6. #include <Authenticate.h>
  7. #include "CustomScpExplorer.h"
  8. #include "LogMemo.h"
  9. #include "NonVisual.h"
  10. #include "WinConfiguration.h"
  11. #include "Tools.h"
  12. #include <Log.h>
  13. #include <Common.h>
  14. #include <CoreMain.h>
  15. #include <GUITools.h>
  16. #include <TextsWin.h>
  17. #include <TextsCore.h>
  18. #include <Progress.h>
  19. #include <Exceptions.h>
  20. #include <VCLCommon.h>
  21. #include <WinApi.h>
  22. //---------------------------------------------------------------------------
  23. #pragma package(smart_init)
  24. //---------------------------------------------------------------------------
  25. TTerminalManager * TTerminalManager::FInstance = NULL;
  26. //---------------------------------------------------------------------------
  27. __fastcall TManagedTerminal::TManagedTerminal(TSessionData * SessionData,
  28. TConfiguration * Configuration) :
  29. TTerminal(SessionData, Configuration),
  30. Color((TColor)SessionData->Color), SynchronizeBrowsing(SessionData->SynchronizeBrowsing),
  31. LocalDirectory(::ExpandFileName(SessionData->LocalDirectory)),
  32. RemoteDirectory(SessionData->RemoteDirectory),
  33. LocalExplorerState(NULL), RemoteExplorerState(NULL),
  34. ReopenStart(0), DirectoryLoaded(Now()), TerminalThread(NULL)
  35. {
  36. }
  37. //---------------------------------------------------------------------------
  38. __fastcall TManagedTerminal::~TManagedTerminal()
  39. {
  40. delete LocalExplorerState;
  41. delete RemoteExplorerState;
  42. }
  43. //---------------------------------------------------------------------------
  44. //---------------------------------------------------------------------------
  45. TTerminalManager * __fastcall TTerminalManager::Instance(bool ForceCreation)
  46. {
  47. if (!FInstance && ForceCreation)
  48. {
  49. FInstance = new TTerminalManager();
  50. }
  51. return FInstance;
  52. }
  53. //---------------------------------------------------------------------------
  54. void __fastcall TTerminalManager::DestroyInstance()
  55. {
  56. assert(FInstance);
  57. SAFE_DESTROY(FInstance);
  58. }
  59. //---------------------------------------------------------------------------
  60. __fastcall TTerminalManager::TTerminalManager() :
  61. TTerminalList(Configuration)
  62. {
  63. FQueueSection = new TCriticalSection();
  64. FLogMemo = NULL;
  65. FActiveTerminal = NULL;
  66. FScpExplorer = NULL;
  67. FDestroying = false;
  68. FTerminalPendingAction = tpNull;
  69. FDirectoryReadingStart = 0;
  70. FAuthenticateForm = NULL;
  71. FTaskbarList = NULL;
  72. FAuthenticating = 0;
  73. assert(Application && !Application->OnException);
  74. Application->OnException = ApplicationException;
  75. assert(Application->OnShowHint == NULL);
  76. Application->OnShowHint = ApplicationShowHint;
  77. assert(Application->OnMessage == NULL);
  78. Application->OnMessage = ApplicationMessage;
  79. assert(Application->OnModalBegin == NULL);
  80. Application->OnModalBegin = ApplicationModalBegin;
  81. assert(Application->OnModalEnd == NULL);
  82. Application->OnModalEnd = ApplicationModalEnd;
  83. assert(WinConfiguration->OnMasterPasswordPrompt == NULL);
  84. WinConfiguration->OnMasterPasswordPrompt = MasterPasswordPrompt;
  85. InitTaskbarButtonCreatedMessage();
  86. assert(Configuration && !Configuration->OnChange);
  87. Configuration->OnChange = ConfigurationChange;
  88. FOnLastTerminalClosed = NULL;
  89. FOnTerminalListChanged = NULL;
  90. FTerminalList = new TStringList();
  91. FQueues = new TList();
  92. FTerminationMessages = new TStringList();
  93. }
  94. //---------------------------------------------------------------------------
  95. __fastcall TTerminalManager::~TTerminalManager()
  96. {
  97. FreeAll();
  98. assert(!ScpExplorer);
  99. assert(Configuration->OnChange == ConfigurationChange);
  100. Configuration->OnChange = NULL;
  101. assert(Application && (Application->OnException == ApplicationException));
  102. Application->OnException = NULL;
  103. assert(Application->OnShowHint == ApplicationShowHint);
  104. Application->OnShowHint = ApplicationShowHint;
  105. assert(Application->OnMessage == ApplicationMessage);
  106. Application->OnMessage = NULL;
  107. assert(Application->OnModalBegin == ApplicationModalBegin);
  108. Application->OnModalBegin = NULL;
  109. assert(Application->OnModalEnd == ApplicationModalEnd);
  110. Application->OnModalEnd = NULL;
  111. assert(WinConfiguration->OnMasterPasswordPrompt == MasterPasswordPrompt);
  112. WinConfiguration->OnMasterPasswordPrompt = NULL;
  113. delete FQueues;
  114. delete FTerminationMessages;
  115. delete FTerminalList;
  116. delete FAuthenticateForm;
  117. delete FQueueSection;
  118. ReleaseTaskbarList();
  119. }
  120. //---------------------------------------------------------------------------
  121. void __fastcall TTerminalManager::SetQueueConfiguration(TTerminalQueue * Queue)
  122. {
  123. Queue->TransfersLimit = GUIConfiguration->QueueTransfersLimit;
  124. Queue->KeepDoneItemsFor =
  125. (GUIConfiguration->QueueKeepDoneItems ? GUIConfiguration->QueueKeepDoneItemsFor : 0);
  126. }
  127. //---------------------------------------------------------------------------
  128. TTerminalQueue * __fastcall TTerminalManager::NewQueue(TTerminal * Terminal)
  129. {
  130. TTerminalQueue * Queue = new TTerminalQueue(Terminal, Configuration);
  131. SetQueueConfiguration(Queue);
  132. Queue->Enabled = WinConfiguration->EnableQueueByDefault;
  133. Queue->OnQueryUser = TerminalQueryUser;
  134. Queue->OnPromptUser = TerminalPromptUser;
  135. Queue->OnShowExtendedException = TerminalShowExtendedException;
  136. Queue->OnEvent = QueueEvent;
  137. return Queue;
  138. }
  139. //---------------------------------------------------------------------------
  140. TTerminal * __fastcall TTerminalManager::CreateTerminal(TSessionData * Data)
  141. {
  142. return new TManagedTerminal(Data, Configuration);
  143. }
  144. //---------------------------------------------------------------------------
  145. TTerminal * __fastcall TTerminalManager::DoNewTerminal(TSessionData * Data)
  146. {
  147. FTerminalList->Clear();
  148. TTerminal * Terminal = TTerminalList::NewTerminal(Data);
  149. try
  150. {
  151. FQueues->Add(NewQueue(Terminal));
  152. FTerminationMessages->Add(L"");
  153. Terminal->OnQueryUser = TerminalQueryUser;
  154. Terminal->OnPromptUser = TerminalPromptUser;
  155. Terminal->OnDisplayBanner = TerminalDisplayBanner;
  156. Terminal->OnShowExtendedException = TerminalShowExtendedException;
  157. Terminal->OnProgress = OperationProgress;
  158. Terminal->OnFinished = OperationFinished;
  159. Terminal->OnDeleteLocalFile = DeleteLocalFile;
  160. Terminal->OnReadDirectoryProgress = TerminalReadDirectoryProgress;
  161. Terminal->OnInformation = TerminalInformation;
  162. }
  163. catch(...)
  164. {
  165. if (Terminal != NULL)
  166. {
  167. FreeTerminal(Terminal);
  168. }
  169. throw;
  170. }
  171. return Terminal;
  172. }
  173. //---------------------------------------------------------------------------
  174. TTerminal * __fastcall TTerminalManager::NewTerminal(TSessionData * Data)
  175. {
  176. TTerminal * Terminal = DoNewTerminal(Data);
  177. DoTerminalListChanged();
  178. return Terminal;
  179. }
  180. //---------------------------------------------------------------------------
  181. TTerminal * __fastcall TTerminalManager::NewTerminals(TList * DataList)
  182. {
  183. TTerminal * Result = NULL;
  184. for (int Index = 0; Index < DataList->Count; Index++)
  185. {
  186. TTerminal * Terminal =
  187. NewTerminal(reinterpret_cast<TSessionData *>(DataList->Items[Index]));
  188. if (Index == 0)
  189. {
  190. Result = Terminal;
  191. }
  192. }
  193. DoTerminalListChanged();
  194. return Result;
  195. }
  196. //---------------------------------------------------------------------------
  197. void __fastcall TTerminalManager::FreeActiveTerminal()
  198. {
  199. if (FTerminalPendingAction == tpNull)
  200. {
  201. assert(ActiveTerminal);
  202. FreeTerminal(ActiveTerminal);
  203. }
  204. else
  205. {
  206. assert(FTerminalPendingAction == ::tpNone);
  207. FTerminalPendingAction = tpFree;
  208. }
  209. }
  210. //---------------------------------------------------------------------------
  211. void TTerminalManager::ConnectTerminal(TTerminal * Terminal, bool Reopen)
  212. {
  213. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  214. // it must be managed terminal, unless it is secondary terminal (of managed terminal)
  215. assert((ManagedTerminal != NULL) || (dynamic_cast<TSecondaryTerminal *>(Terminal) != NULL));
  216. // particularly when we are reconnecting RemoteDirectory of managed terminal
  217. // hold the last used remote directory as opposite to session data, which holds
  218. // the default remote directory.
  219. // make sure the last used directory is used, but the default is preserved too
  220. UnicodeString OrigRemoteDirectory = Terminal->SessionData->RemoteDirectory;
  221. try
  222. {
  223. TTerminalThread * TerminalThread = new TTerminalThread(Terminal);
  224. try
  225. {
  226. if (ManagedTerminal != NULL)
  227. {
  228. Terminal->SessionData->RemoteDirectory = ManagedTerminal->RemoteDirectory;
  229. if ((double)ManagedTerminal->ReopenStart == 0)
  230. {
  231. ManagedTerminal->ReopenStart = Now();
  232. }
  233. assert(ManagedTerminal->TerminalThread == NULL);
  234. ManagedTerminal->TerminalThread = TerminalThread;
  235. }
  236. TNotifyEvent OnIdle;
  237. ((TMethod*)&OnIdle)->Code = TerminalThreadIdle;
  238. TerminalThread->OnIdle = OnIdle;
  239. if (Reopen)
  240. {
  241. TerminalThread->TerminalReopen();
  242. }
  243. else
  244. {
  245. TerminalThread->TerminalOpen();
  246. }
  247. }
  248. __finally
  249. {
  250. if (ManagedTerminal != NULL)
  251. {
  252. ManagedTerminal->TerminalThread = NULL;
  253. }
  254. delete TerminalThread;
  255. }
  256. }
  257. __finally
  258. {
  259. Terminal->SessionData->RemoteDirectory = OrigRemoteDirectory;
  260. if (Terminal->Active && (ManagedTerminal != NULL))
  261. {
  262. ManagedTerminal->ReopenStart = 0;
  263. }
  264. }
  265. }
  266. //---------------------------------------------------------------------------
  267. void __fastcall TTerminalManager::TerminalThreadIdle(void * /*Data*/, TObject * /*Sender*/)
  268. {
  269. Application->ProcessMessages();
  270. }
  271. //---------------------------------------------------------------------------
  272. bool __fastcall TTerminalManager::ConnectActiveTerminalImpl(bool Reopen)
  273. {
  274. TTerminalPendingAction Action;
  275. bool Result;
  276. do
  277. {
  278. Action = tpNull;
  279. Result = false;
  280. try
  281. {
  282. assert(ActiveTerminal);
  283. bool ShowLogPending = false;
  284. if (Configuration->Logging && (WinConfiguration->LogView == lvWindow))
  285. {
  286. if (WinConfiguration->LogWindowOnStartup)
  287. {
  288. RequireLogForm(LogMemo);
  289. }
  290. else
  291. {
  292. ShowLogPending = true;
  293. }
  294. }
  295. ConnectTerminal(ActiveTerminal, Reopen);
  296. if (ScpExplorer)
  297. {
  298. assert(ActiveTerminal->Status == ssOpened);
  299. TerminalReady();
  300. }
  301. WinConfiguration->ClearTemporaryLoginData();
  302. if (LogForm && (WinConfiguration->LogView != lvWindow))
  303. {
  304. FreeLogForm();
  305. }
  306. if (ShowLogPending)
  307. {
  308. RequireLogForm(LogMemo);
  309. }
  310. Result = true;
  311. }
  312. catch(Exception & E)
  313. {
  314. assert(FTerminalPendingAction == tpNull);
  315. FTerminalPendingAction = ::tpNone;
  316. try
  317. {
  318. assert(ActiveTerminal != NULL);
  319. ActiveTerminal->ShowExtendedException(&E);
  320. Action = FTerminalPendingAction;
  321. }
  322. __finally
  323. {
  324. FTerminalPendingAction = tpNull;
  325. }
  326. }
  327. }
  328. while (Action == tpReconnect);
  329. if (Action == tpFree)
  330. {
  331. FreeActiveTerminal();
  332. }
  333. return Result;
  334. }
  335. //---------------------------------------------------------------------------
  336. bool __fastcall TTerminalManager::ConnectActiveTerminal()
  337. {
  338. ActiveTerminal->CollectUsage();
  339. // add only stored sessions to the jump list,
  340. // ad-hoc session cannot be reproduced from just a session name
  341. if (StoredSessions->FindSame(ActiveTerminal->SessionData) != NULL)
  342. {
  343. WinConfiguration->AddSessionToJumpList(ActiveTerminal->SessionData->SessionName);
  344. }
  345. FAuthenticationCancelled = false;
  346. bool Result = ConnectActiveTerminalImpl(false);
  347. UnicodeString DateStamp = StandardDatestamp();
  348. if (Result)
  349. {
  350. if (Configuration->Usage->Get(L"OpenedSessionsFailedLastDate") == DateStamp)
  351. {
  352. Configuration->Usage->Inc(L"OpenedSessionsFailedRecovered");
  353. }
  354. }
  355. else
  356. {
  357. Configuration->Usage->Inc(L"OpenedSessionsFailed");
  358. Configuration->Usage->Set(L"OpenedSessionsFailedLastDate", DateStamp);
  359. if (FAuthenticationCancelled)
  360. {
  361. Configuration->Usage->Inc(L"OpenedSessionsFailedAfterCancel");
  362. }
  363. }
  364. if (Result && WinConfiguration->AutoOpenInPutty && CanOpenInPutty())
  365. {
  366. try
  367. {
  368. OpenInPutty();
  369. }
  370. catch(Exception & E)
  371. {
  372. ShowExtendedExceptionEx(NULL, &E);
  373. }
  374. }
  375. return Result;
  376. }
  377. //---------------------------------------------------------------------------
  378. void __fastcall TTerminalManager::DisconnectActiveTerminal()
  379. {
  380. assert(ActiveTerminal);
  381. int Index = IndexOf(ActiveTerminal);
  382. TTerminalQueue * OldQueue;
  383. TTerminalQueue * NewQueue;
  384. OldQueue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  385. NewQueue = this->NewQueue(ActiveTerminal);
  386. FQueues->Items[Index] = NewQueue;
  387. ScpExplorer->Queue = NewQueue;
  388. delete OldQueue;
  389. }
  390. //---------------------------------------------------------------------------
  391. void __fastcall TTerminalManager::ReconnectActiveTerminal()
  392. {
  393. assert(ActiveTerminal);
  394. if (ScpExplorer)
  395. {
  396. if (ScpExplorer->Terminal == ActiveTerminal)
  397. {
  398. ScpExplorer->UpdateTerminal(ActiveTerminal);
  399. }
  400. }
  401. try
  402. {
  403. if (FTerminalPendingAction == tpNull)
  404. {
  405. ConnectActiveTerminalImpl(true);
  406. }
  407. else
  408. {
  409. FTerminalPendingAction = tpReconnect;
  410. }
  411. }
  412. catch(...)
  413. {
  414. FreeActiveTerminal();
  415. throw;
  416. }
  417. }
  418. //---------------------------------------------------------------------------
  419. void __fastcall TTerminalManager::FreeAll()
  420. {
  421. FDestroying = true;
  422. try
  423. {
  424. while (Count)
  425. {
  426. FreeTerminal(Terminals[0]);
  427. }
  428. }
  429. __finally
  430. {
  431. FDestroying = false;
  432. }
  433. }
  434. //---------------------------------------------------------------------------
  435. void __fastcall TTerminalManager::FreeTerminal(TTerminal * Terminal)
  436. {
  437. try
  438. {
  439. // we want the Login dialog to open on auto-workspace name,
  440. // as set in TCustomScpExplorerForm::FormClose
  441. if (!FDestroying || !WinConfiguration->AutoSaveWorkspace)
  442. {
  443. if (StoredSessions->FindSame(Terminal->SessionData) != NULL)
  444. {
  445. WinConfiguration->LastStoredSession = Terminal->SessionData->Name;
  446. }
  447. }
  448. if (ScpExplorer != NULL)
  449. {
  450. ScpExplorer->TerminalRemoved(Terminal);
  451. }
  452. if (Terminal->Active)
  453. {
  454. Terminal->Close();
  455. }
  456. }
  457. __finally
  458. {
  459. int Index = IndexOf(Terminal);
  460. FTerminalList->Clear();
  461. Extract(Terminal);
  462. TTerminalQueue * Queue;
  463. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  464. FQueues->Delete(Index);
  465. FTerminationMessages->Delete(Index);
  466. if (ActiveTerminal && (Terminal == ActiveTerminal))
  467. {
  468. if ((Count > 0) && !FDestroying)
  469. {
  470. ActiveTerminal = Terminals[Index < Count ? Index : Index - 1];
  471. }
  472. else
  473. {
  474. ActiveTerminal = NULL;
  475. }
  476. }
  477. else
  478. {
  479. SaveTerminal(Terminal);
  480. }
  481. // only now all references to/from queue (particularly events to explorer)
  482. // are cleared
  483. delete Queue;
  484. delete Terminal;
  485. DoTerminalListChanged();
  486. }
  487. }
  488. //---------------------------------------------------------------------------
  489. void __fastcall TTerminalManager::SetScpExplorer(TCustomScpExplorerForm * value)
  490. {
  491. if (ScpExplorer != value)
  492. {
  493. // changing explorer is not supported yet
  494. assert(!ScpExplorer || !value);
  495. FScpExplorer = value;
  496. if (FScpExplorer)
  497. {
  498. FScpExplorer->Terminal = ActiveTerminal;
  499. FScpExplorer->Queue = ActiveQueue;
  500. FOnLastTerminalClosed = FScpExplorer->LastTerminalClosed;
  501. FOnTerminalListChanged = FScpExplorer->TerminalListChanged;
  502. UpdateTaskbarList();
  503. }
  504. else
  505. {
  506. FOnLastTerminalClosed = NULL;
  507. FOnTerminalListChanged = NULL;
  508. }
  509. }
  510. }
  511. //---------------------------------------------------------------------------
  512. void __fastcall TTerminalManager::SetActiveTerminal(TTerminal * value)
  513. {
  514. DoSetActiveTerminal(value, false);
  515. }
  516. //---------------------------------------------------------------------------
  517. void __fastcall TTerminalManager::SetActiveTerminalWithAutoReconnect(TTerminal * value)
  518. {
  519. DoSetActiveTerminal(value, true);
  520. }
  521. //---------------------------------------------------------------------------
  522. void __fastcall TTerminalManager::DoSetActiveTerminal(TTerminal * value, bool AutoReconnect)
  523. {
  524. if (ActiveTerminal != value)
  525. {
  526. // here used to be call to TCustomScpExporer::UpdateSessionData (now UpdateTerminal)
  527. // but it seems to be duplicate to call from TCustomScpExporer::TerminalChanging
  528. TTerminal * PActiveTerminal = ActiveTerminal;
  529. FActiveTerminal = value;
  530. // moved from else block of next if (ActiveTerminal) statement
  531. // so ScpExplorer can update its caption
  532. UpdateAppTitle();
  533. if (ScpExplorer)
  534. {
  535. if (ActiveTerminal && (ActiveTerminal->Status == ssOpened))
  536. {
  537. TerminalReady();
  538. }
  539. else
  540. {
  541. ScpExplorer->Terminal = NULL;
  542. ScpExplorer->Queue = NULL;
  543. }
  544. }
  545. if (PActiveTerminal && !PActiveTerminal->Active)
  546. {
  547. SaveTerminal(PActiveTerminal);
  548. }
  549. if (ActiveTerminal)
  550. {
  551. if (!PActiveTerminal)
  552. {
  553. CreateLogMemo();
  554. }
  555. assert(LogMemo);
  556. LogMemo->SessionLog = ActiveTerminal->Log;
  557. int Index = ActiveTerminalIndex;
  558. if (!ActiveTerminal->Active && !FTerminationMessages->Strings[Index].IsEmpty())
  559. {
  560. UnicodeString Message = FTerminationMessages->Strings[Index];
  561. FTerminationMessages->Strings[Index] = L"";
  562. if (AutoReconnect)
  563. {
  564. ReconnectActiveTerminal();
  565. }
  566. else
  567. {
  568. Exception * E = new ESshFatal(NULL, Message);
  569. try
  570. {
  571. // finally show pending terminal message,
  572. // this gives user also possibility to reconnect
  573. ActiveTerminal->ShowExtendedException(E);
  574. }
  575. __finally
  576. {
  577. delete E;
  578. }
  579. }
  580. }
  581. }
  582. else
  583. {
  584. if (LogForm)
  585. {
  586. FreeLogForm();
  587. }
  588. FreeLogMemo();
  589. if (OnLastTerminalClosed)
  590. {
  591. OnLastTerminalClosed(this);
  592. }
  593. }
  594. if ((ActiveTerminal != NULL) && !ActiveTerminal->Active)
  595. {
  596. ConnectActiveTerminal();
  597. }
  598. }
  599. }
  600. //---------------------------------------------------------------------------
  601. void __fastcall TTerminalManager::QueueStatusUpdated()
  602. {
  603. UpdateAppTitle();
  604. }
  605. //---------------------------------------------------------------------------
  606. void __fastcall TTerminalManager::UpdateAppTitle()
  607. {
  608. if (ScpExplorer)
  609. {
  610. UnicodeString NewTitle;
  611. if (ActiveTerminal)
  612. {
  613. NewTitle = FormatMainFormCaption(ActiveTerminalTitle);
  614. }
  615. else
  616. {
  617. NewTitle = FormatMainFormCaption(L"");
  618. }
  619. UnicodeString QueueProgressTitle;
  620. if (!FForegroundProgressTitle.IsEmpty())
  621. {
  622. NewTitle = FForegroundProgressTitle + L" - " + NewTitle;
  623. }
  624. else if (!FProgressTitle.IsEmpty() && !ForegroundTask())
  625. {
  626. NewTitle = FProgressTitle + L" - " + NewTitle;
  627. }
  628. else if ((ScpExplorer != NULL) && (ScpExplorer->Handle != GetAncestor(GetActiveWindow(), GA_ROOTOWNER)) &&
  629. !(QueueProgressTitle = ScpExplorer->GetQueueProgressTitle()).IsEmpty())
  630. {
  631. NewTitle = QueueProgressTitle + L" - " + NewTitle;
  632. }
  633. else if (ActiveTerminal && (ScpExplorer != NULL))
  634. {
  635. UnicodeString Path = ScpExplorer->PathForCaption();
  636. if (!Path.IsEmpty())
  637. {
  638. NewTitle = Path + L" - " + NewTitle;
  639. }
  640. }
  641. ScpExplorer->Caption = NewTitle;
  642. ScpExplorer->ApplicationTitleChanged();
  643. }
  644. }
  645. //---------------------------------------------------------------------------
  646. void __fastcall TTerminalManager::SaveTerminal(TTerminal * Terminal)
  647. {
  648. TSessionData * Data = StoredSessions->FindSame(Terminal->SessionData);
  649. if (Data != NULL)
  650. {
  651. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  652. assert(ManagedTerminal != NULL);
  653. bool Changed = false;
  654. if (Terminal->SessionData->UpdateDirectories)
  655. {
  656. Data->LocalDirectory = ManagedTerminal->LocalDirectory;
  657. Data->RemoteDirectory = ManagedTerminal->RemoteDirectory;
  658. Data->SynchronizeBrowsing = ManagedTerminal->SynchronizeBrowsing;
  659. Changed = true;
  660. }
  661. if (Changed)
  662. {
  663. // modified only, implicit
  664. StoredSessions->Save(false, false);
  665. }
  666. }
  667. }
  668. //---------------------------------------------------------------------------
  669. void __fastcall TTerminalManager::CreateLogMemo()
  670. {
  671. assert(!FLogMemo);
  672. assert(ActiveTerminal);
  673. FLogMemo = new TLogMemo(Application);
  674. try
  675. {
  676. FLogMemo->SessionLog = ActiveTerminal->Log;
  677. FLogMemo->PopupMenu = NonVisualDataModule->LogMemoPopup;
  678. }
  679. catch (...)
  680. {
  681. delete FLogMemo;
  682. throw;
  683. }
  684. }
  685. //---------------------------------------------------------------------------
  686. void __fastcall TTerminalManager::FreeLogMemo()
  687. {
  688. assert(LogMemo);
  689. LogMemo->PopupMenu = NULL;
  690. SAFE_DESTROY(FLogMemo);
  691. }
  692. //---------------------------------------------------------------------------
  693. void __fastcall TTerminalManager::HandleException(Exception * E)
  694. {
  695. // can be null for example when exception is thrown on login dialog
  696. if (ActiveTerminal != NULL)
  697. {
  698. ActiveTerminal->ShowExtendedException(E);
  699. }
  700. else
  701. {
  702. ShowExtendedException(E);
  703. }
  704. }
  705. //---------------------------------------------------------------------------
  706. void __fastcall TTerminalManager::ApplicationException(TObject * /*Sender*/,
  707. Exception * E)
  708. {
  709. HandleException(E);
  710. }
  711. //---------------------------------------------------------------------------
  712. void __fastcall TTerminalManager::ApplicationShowHint(UnicodeString & HintStr,
  713. bool & /*CanShow*/, THintInfo & HintInfo)
  714. {
  715. TLabel * HintLabel = dynamic_cast<TLabel *>(HintInfo.HintControl);
  716. if ((HintLabel != NULL) && (HintLabel->Caption == HintStr))
  717. {
  718. // Hack for transfer setting labels.
  719. // Should be converted to something like HintLabel()
  720. HintInfo.HintPos = HintLabel->ClientToScreen(TPoint(0, 0));
  721. HintInfo.HintMaxWidth = HintLabel->Width;
  722. HintInfo.HideTimeout = 100000; // "almost" never
  723. }
  724. else if (dynamic_cast<TProgressBar *>(HintInfo.HintControl) != NULL)
  725. {
  726. // Hint is forcibly hidden in TProgressForm::FormHide
  727. HintInfo.HideTimeout = 100000; // "almost" never
  728. HintInfo.ReshowTimeout = 500; // updated each 0.5s
  729. }
  730. else
  731. {
  732. HintInfo.HintMaxWidth = 300;
  733. }
  734. }
  735. //---------------------------------------------------------------------------
  736. void __fastcall TTerminalManager::ApplicationMessage(TMsg & Msg, bool & Handled)
  737. {
  738. if (Msg.message == FTaskbarButtonCreatedMessage)
  739. {
  740. CreateTaskbarList();
  741. }
  742. if ((Msg.message == WM_MOUSEWHEEL) && (ScpExplorer != NULL))
  743. {
  744. Handled = ScpExplorer->HandleMouseWheel(Msg.wParam, Msg.lParam);
  745. }
  746. }
  747. //---------------------------------------------------------------------------
  748. void __fastcall TTerminalManager::ApplicationModalBegin(TObject * /*Sender*/)
  749. {
  750. NonVisualDataModule->StartBusy();
  751. if (ScpExplorer != NULL)
  752. {
  753. ScpExplorer->SuspendWindowLock();
  754. }
  755. }
  756. //---------------------------------------------------------------------------
  757. void __fastcall TTerminalManager::ApplicationModalEnd(TObject * /*Sender*/)
  758. {
  759. NonVisualDataModule->EndBusy();
  760. if (ScpExplorer != NULL)
  761. {
  762. ScpExplorer->ResumeWindowLock();
  763. }
  764. }
  765. //---------------------------------------------------------------------------
  766. void __fastcall TTerminalManager::InitTaskbarButtonCreatedMessage()
  767. {
  768. // XE6 VCL already handles TaskbarButtonCreated, but does not call ChangeWindowMessageFilterEx.
  769. // So we keep our implementation.
  770. // See also http://stackoverflow.com/a/14618587/850848
  771. FTaskbarButtonCreatedMessage = RegisterWindowMessage(L"TaskbarButtonCreated");
  772. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  773. ChangeWindowMessageFilterExProc ChangeWindowMessageFilterEx =
  774. (ChangeWindowMessageFilterExProc)GetProcAddress(User32Library, "ChangeWindowMessageFilterEx");
  775. if (ChangeWindowMessageFilterEx != NULL)
  776. {
  777. // without this we won't get TaskbarButtonCreated, when app is running elevated
  778. ChangeWindowMessageFilterEx(
  779. Application->Handle, FTaskbarButtonCreatedMessage, MSGFLT_ALLOW, NULL);
  780. }
  781. }
  782. //---------------------------------------------------------------------------
  783. void __fastcall TTerminalManager::CreateTaskbarList()
  784. {
  785. ReleaseTaskbarList();
  786. if(SUCCEEDED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL,
  787. IID_ITaskbarList3, (void **) &FTaskbarList)))
  788. {
  789. if (ScpExplorer != NULL)
  790. {
  791. UpdateTaskbarList();
  792. }
  793. }
  794. }
  795. //---------------------------------------------------------------------------
  796. void __fastcall TTerminalManager::ReleaseTaskbarList()
  797. {
  798. if (FTaskbarList != NULL)
  799. {
  800. FTaskbarList->Release();
  801. }
  802. }
  803. //---------------------------------------------------------------------------
  804. void __fastcall TTerminalManager::UpdateTaskbarList()
  805. {
  806. ScpExplorer->UpdateTaskbarList(FTaskbarList);
  807. }
  808. //---------------------------------------------------------------------------
  809. void __fastcall TTerminalManager::DeleteLocalFile(const UnicodeString FileName, bool Alternative)
  810. {
  811. if (!RecursiveDeleteFile(FileName, (WinConfiguration->DeleteToRecycleBin != Alternative)))
  812. {
  813. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  814. }
  815. }
  816. //---------------------------------------------------------------------------
  817. void __fastcall TTerminalManager::TerminalQueryUser(TObject * Sender,
  818. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  819. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * /*Arg*/)
  820. {
  821. UnicodeString HelpKeyword;
  822. TMessageParams MessageParams(Params);
  823. UnicodeString AQuery = Query;
  824. if (Params != NULL)
  825. {
  826. HelpKeyword = Params->HelpKeyword;
  827. if (FLAGSET(Params->Params, qpFatalAbort))
  828. {
  829. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  830. if (!MessageParams.TimerMessage.IsEmpty())
  831. {
  832. MessageParams.TimerMessage = FMTLOAD(WARN_FATAL_ERROR, (MessageParams.TimerMessage));
  833. }
  834. }
  835. }
  836. if (ScpExplorer)
  837. {
  838. Answer = ScpExplorer->MoreMessageDialog(AQuery, MoreMessages, Type, Answers,
  839. HelpKeyword, &MessageParams, dynamic_cast<TTerminal *>(Sender));
  840. }
  841. else
  842. {
  843. Answer = MoreMessageDialog(AQuery, MoreMessages, Type, Answers, HelpKeyword,
  844. &MessageParams);
  845. }
  846. }
  847. //---------------------------------------------------------------------------
  848. void __fastcall TTerminalManager::AuthenticateFormCancel(TObject * Sender)
  849. {
  850. TAuthenticateForm * Form = dynamic_cast<TAuthenticateForm *>(Sender);
  851. assert(Form != NULL);
  852. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Form->Terminal);
  853. // will be null e.g. for background transfers
  854. if (ManagedTerminal != NULL)
  855. {
  856. TTerminalThread * TerminalThread = ManagedTerminal->TerminalThread;
  857. // can be NULL for reconnects from transfers
  858. if ((TerminalThread != NULL) && !TerminalThread->Cancelling)
  859. {
  860. Form->Log(LoadStr(AUTH_CANCELLING));
  861. TerminalThread->Cancel();
  862. }
  863. }
  864. FAuthenticationCancelled = true;
  865. }
  866. //---------------------------------------------------------------------------
  867. TAuthenticateForm * __fastcall TTerminalManager::MakeAuthenticateForm(
  868. TTerminal * Terminal)
  869. {
  870. TAuthenticateForm * Dialog = SafeFormCreate<TAuthenticateForm>();
  871. Dialog->Init(Terminal);
  872. assert(Dialog->OnCancel == NULL);
  873. Dialog->OnCancel = AuthenticateFormCancel;
  874. return Dialog;
  875. }
  876. //---------------------------------------------------------------------------
  877. void __fastcall TTerminalManager::FileNameInputDialogInitializeRenameBaseName(
  878. TObject * /*Sender*/, TInputDialogData * Data)
  879. {
  880. EditSelectBaseName(Data->Edit->Handle);
  881. }
  882. //---------------------------------------------------------------------------
  883. void __fastcall TTerminalManager::TerminalPromptUser(
  884. TTerminal * Terminal, TPromptKind Kind, UnicodeString Name, UnicodeString Instructions,
  885. TStrings * Prompts, TStrings * Results, bool & Result, void * /*Arg*/)
  886. {
  887. if (((Kind == pkPrompt) || (Kind == pkFileName)) && (FAuthenticateForm == NULL) &&
  888. (Terminal->Status != ssOpening))
  889. {
  890. assert(Instructions.IsEmpty());
  891. assert(Prompts->Count == 1);
  892. assert(FLAGSET(int(Prompts->Objects[0]), pupEcho));
  893. UnicodeString AResult = Results->Strings[0];
  894. TInputDialogInitialize InputDialogInitialize = NULL;
  895. if ((Kind == pkFileName) && !WinConfiguration->RenameWholeName)
  896. {
  897. InputDialogInitialize = FileNameInputDialogInitializeRenameBaseName;
  898. }
  899. Result = InputDialog(Name, Prompts->Strings[0], AResult, L"", NULL, false, InputDialogInitialize);
  900. if (Result)
  901. {
  902. Results->Strings[0] = AResult;
  903. }
  904. }
  905. else
  906. {
  907. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  908. if (AuthenticateForm == NULL)
  909. {
  910. AuthenticateForm = MakeAuthenticateForm(Terminal);
  911. }
  912. try
  913. {
  914. Result = AuthenticateForm->PromptUser(Kind, Name, Instructions, Prompts, Results,
  915. (FAuthenticateForm != NULL), Terminal->StoredCredentialsTried);
  916. }
  917. __finally
  918. {
  919. if (FAuthenticateForm == NULL)
  920. {
  921. delete AuthenticateForm;
  922. }
  923. }
  924. }
  925. }
  926. //---------------------------------------------------------------------------
  927. void __fastcall TTerminalManager::TerminalDisplayBanner(
  928. TTerminal * Terminal, UnicodeString SessionName,
  929. const UnicodeString & Banner, bool & NeverShowAgain, int Options)
  930. {
  931. assert(FAuthenticateForm != NULL);
  932. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  933. if (AuthenticateForm == NULL)
  934. {
  935. AuthenticateForm = MakeAuthenticateForm(Terminal);
  936. }
  937. try
  938. {
  939. AuthenticateForm->Banner(Banner, NeverShowAgain, Options);
  940. }
  941. __finally
  942. {
  943. if (FAuthenticateForm == NULL)
  944. {
  945. delete AuthenticateForm;
  946. }
  947. }
  948. }
  949. //---------------------------------------------------------------------------
  950. void __fastcall TTerminalManager::TerminalShowExtendedException(
  951. TTerminal * Terminal, Exception * E, void * /*Arg*/)
  952. {
  953. if (ScpExplorer)
  954. {
  955. ScpExplorer->ShowExtendedException(Terminal, E);
  956. }
  957. else
  958. {
  959. ShowExtendedExceptionEx(Terminal, E);
  960. }
  961. }
  962. //---------------------------------------------------------------------------
  963. static TDateTime DirectoryReadingProgressDelay(0, 0, 1, 500);
  964. //---------------------------------------------------------------------------
  965. void __fastcall TTerminalManager::TerminalReadDirectoryProgress(
  966. TObject * /*Sender*/, int Progress, int ResolvedLinks, bool & Cancel)
  967. {
  968. if (Progress == 0)
  969. {
  970. if (ScpExplorer != NULL)
  971. {
  972. ScpExplorer->LockWindow();
  973. }
  974. FDirectoryReadingStart = Now();
  975. if (!FProgressTitle.IsEmpty() || !FForegroundProgressTitle.IsEmpty())
  976. {
  977. FProgressTitle = L"";
  978. FForegroundProgressTitle = L"";
  979. UpdateAppTitle();
  980. }
  981. // Reset "was ESC ever pressed?" state
  982. GetAsyncKeyState(VK_ESCAPE);
  983. }
  984. else if (Progress < 0)
  985. {
  986. if (Progress == -2)
  987. {
  988. // cancelled
  989. if (ScpExplorer != NULL)
  990. {
  991. ScpExplorer->ReadDirectoryCancelled();
  992. }
  993. }
  994. else
  995. {
  996. if (ScpExplorer != NULL)
  997. {
  998. ScpExplorer->UnlockWindow();
  999. }
  1000. FProgressTitle = L"";
  1001. FForegroundProgressTitle = L"";
  1002. UpdateAppTitle();
  1003. }
  1004. }
  1005. else
  1006. {
  1007. // If the least significant bit is set,
  1008. // the key was pressed after the previous call to GetAsyncKeyState.
  1009. int KeyState = GetAsyncKeyState(VK_ESCAPE);
  1010. if (FLAGSET(KeyState, 0x01))
  1011. {
  1012. Cancel = true;
  1013. }
  1014. if ((Now() - FDirectoryReadingStart) >= DirectoryReadingProgressDelay)
  1015. {
  1016. // 4 is arbitrary number
  1017. FForegroundProgressTitle =
  1018. FMTLOAD(ResolvedLinks >= 4 ? DIRECTORY_READING_AND_RESOLVING_PROGRESS : DIRECTORY_READING_PROGRESS,
  1019. (Progress));
  1020. UpdateAppTitle();
  1021. }
  1022. }
  1023. }
  1024. //---------------------------------------------------------------------------
  1025. void __fastcall TTerminalManager::TerminalInformation(
  1026. TTerminal * Terminal, const UnicodeString & Str, bool /*Status*/, int Phase)
  1027. {
  1028. if (Phase == 1)
  1029. {
  1030. if (FAuthenticating == 0)
  1031. {
  1032. FBusyToken = BusyStart();
  1033. }
  1034. FAuthenticating++;
  1035. }
  1036. else if (Phase == 0)
  1037. {
  1038. assert(FAuthenticating > 0);
  1039. FAuthenticating--;
  1040. if (FAuthenticating == 0)
  1041. {
  1042. BusyEnd(FBusyToken);
  1043. FBusyToken = NULL;
  1044. }
  1045. SAFE_DESTROY(FAuthenticateForm);
  1046. }
  1047. else
  1048. {
  1049. if (FAuthenticating > 0)
  1050. {
  1051. bool ShowPending = false;
  1052. if (FAuthenticateForm == NULL)
  1053. {
  1054. FAuthenticateForm = MakeAuthenticateForm(Terminal);
  1055. ShowPending = true;
  1056. }
  1057. FAuthenticateForm->Log(Str);
  1058. if (ShowPending)
  1059. {
  1060. FAuthenticateForm->ShowAsModal();
  1061. }
  1062. }
  1063. }
  1064. }
  1065. //---------------------------------------------------------------------------
  1066. void __fastcall TTerminalManager::OperationFinished(::TFileOperation Operation,
  1067. TOperationSide Side, bool Temp, const UnicodeString & FileName, bool Success,
  1068. TOnceDoneOperation & OnceDoneOperation)
  1069. {
  1070. assert(ScpExplorer);
  1071. ScpExplorer->OperationFinished(Operation, Side, Temp, FileName, Success,
  1072. OnceDoneOperation);
  1073. }
  1074. //---------------------------------------------------------------------------
  1075. UnicodeString __fastcall TTerminalManager::ProgressTitle(TFileOperationProgressType * ProgressData)
  1076. {
  1077. return
  1078. FORMAT(L"%d%% %s",
  1079. (ProgressData->OverallProgress(),
  1080. TProgressForm::OperationName(ProgressData->Operation, ProgressData->Side)));
  1081. }
  1082. //---------------------------------------------------------------------------
  1083. void __fastcall TTerminalManager::OperationProgress(
  1084. TFileOperationProgressType & ProgressData)
  1085. {
  1086. if (ProgressData.InProgress)
  1087. {
  1088. FProgressTitle = ProgressTitle(&ProgressData);
  1089. }
  1090. else
  1091. {
  1092. FProgressTitle = L"";
  1093. }
  1094. UpdateAppTitle();
  1095. assert(ScpExplorer);
  1096. ScpExplorer->OperationProgress(ProgressData);
  1097. }
  1098. //---------------------------------------------------------------------------
  1099. void __fastcall TTerminalManager::QueueEvent(TTerminalQueue * Queue, TQueueEvent Event)
  1100. {
  1101. TGuard Guard(FQueueSection);
  1102. FQueueEvents.push_back(std::make_pair(Queue, Event));
  1103. }
  1104. //---------------------------------------------------------------------------
  1105. void __fastcall TTerminalManager::ConfigurationChange(TObject * /*Sender*/)
  1106. {
  1107. assert(Configuration);
  1108. assert(Configuration == WinConfiguration);
  1109. if (!Application->Terminated && Configuration->Logging &&
  1110. (WinConfiguration->LogView == lvWindow))
  1111. {
  1112. if (ActiveTerminal)
  1113. {
  1114. RequireLogForm(LogMemo);
  1115. }
  1116. }
  1117. else
  1118. {
  1119. FreeLogForm();
  1120. }
  1121. TTerminalQueue * Queue;
  1122. for (int Index = 0; Index < Count; Index++)
  1123. {
  1124. assert(Terminals[Index]->Log);
  1125. Terminals[Index]->Log->ReflectSettings();
  1126. Terminals[Index]->ActionLog->ReflectSettings();
  1127. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1128. SetQueueConfiguration(Queue);
  1129. }
  1130. if (ScpExplorer)
  1131. {
  1132. ScpExplorer->ConfigurationChanged();
  1133. }
  1134. }
  1135. //---------------------------------------------------------------------------
  1136. void __fastcall TTerminalManager::TerminalReady()
  1137. {
  1138. ScpExplorer->Terminal = ActiveTerminal;
  1139. ScpExplorer->Queue = ActiveQueue;
  1140. ScpExplorer->TerminalReady();
  1141. }
  1142. //---------------------------------------------------------------------------
  1143. TStrings * __fastcall TTerminalManager::GetTerminalList()
  1144. {
  1145. if (FTerminalList->Count != Count)
  1146. {
  1147. for (int i = 0; i < Count; i++)
  1148. {
  1149. UnicodeString NameN;
  1150. UnicodeString Name = Terminals[i]->SessionData->SessionName;
  1151. int Number = 1;
  1152. NameN = Name;
  1153. while (FTerminalList->IndexOf(NameN) >= 0)
  1154. {
  1155. Number++;
  1156. NameN = FORMAT(L"%s (%d)", (Name, Number));
  1157. }
  1158. if (Number > 1)
  1159. {
  1160. Name = FORMAT(L"%s (%d)", (Name, Number));
  1161. }
  1162. FTerminalList->AddObject(Name, Terminals[i]);
  1163. }
  1164. }
  1165. return FTerminalList;
  1166. }
  1167. //---------------------------------------------------------------------------
  1168. int __fastcall TTerminalManager::GetActiveTerminalIndex()
  1169. {
  1170. return ActiveTerminal ? IndexOf(ActiveTerminal) : -1;
  1171. }
  1172. //---------------------------------------------------------------------------
  1173. void __fastcall TTerminalManager::SetActiveTerminalIndex(int value)
  1174. {
  1175. ActiveTerminal = Terminals[value];
  1176. }
  1177. //---------------------------------------------------------------------------
  1178. UnicodeString __fastcall TTerminalManager::TerminalTitle(TTerminal * Terminal)
  1179. {
  1180. int Index = IndexOf(Terminal);
  1181. UnicodeString Result;
  1182. if (Index >= 0)
  1183. {
  1184. Result = TerminalList->Strings[Index];
  1185. }
  1186. else
  1187. {
  1188. // this is the case of background transfer sessions
  1189. Result = Terminal->SessionData->SessionName;
  1190. }
  1191. return Result;
  1192. }
  1193. //---------------------------------------------------------------------------
  1194. UnicodeString __fastcall TTerminalManager::GetActiveTerminalTitle()
  1195. {
  1196. UnicodeString Result = ActiveTerminal ?
  1197. TerminalTitle(ActiveTerminal) : UnicodeString(L"");
  1198. return Result;
  1199. }
  1200. //---------------------------------------------------------------------------
  1201. TTerminalQueue * __fastcall TTerminalManager::GetActiveQueue()
  1202. {
  1203. TTerminalQueue * Result = NULL;
  1204. if (ActiveTerminal != NULL)
  1205. {
  1206. Result = reinterpret_cast<TTerminalQueue *>(FQueues->Items[ActiveTerminalIndex]);
  1207. }
  1208. return Result;
  1209. }
  1210. //---------------------------------------------------------------------------
  1211. void __fastcall TTerminalManager::CycleTerminals(bool Forward)
  1212. {
  1213. int Index = ActiveTerminalIndex;
  1214. Index += Forward ? 1 : -1;
  1215. if (Index < 0)
  1216. {
  1217. Index = Count-1;
  1218. }
  1219. else if (Index >= Count)
  1220. {
  1221. Index = 0;
  1222. }
  1223. ActiveTerminalIndex = Index;
  1224. }
  1225. //---------------------------------------------------------------------------
  1226. bool __fastcall TTerminalManager::CanOpenInPutty()
  1227. {
  1228. return (ActiveTerminal != NULL) && !GUIConfiguration->PuttyPath.Trim().IsEmpty();
  1229. }
  1230. //---------------------------------------------------------------------------
  1231. void __fastcall TTerminalManager::UpdateSessionCredentials(TSessionData * Data)
  1232. {
  1233. Data->UserName = ActiveTerminal->UserName;
  1234. Data->Password = ActiveTerminal->Password;
  1235. }
  1236. //---------------------------------------------------------------------------
  1237. void __fastcall TTerminalManager::OpenInPutty()
  1238. {
  1239. Configuration->Usage->Inc(L"OpenInPutty");
  1240. TSessionData * Data = NULL;
  1241. try
  1242. {
  1243. // Is NULL on the first session when called from ConnectActiveTerminal()
  1244. // due to WinConfiguration->AutoOpenInPutty
  1245. if (ScpExplorer != NULL)
  1246. {
  1247. Data = ScpExplorer->CloneCurrentSessionData();
  1248. }
  1249. else
  1250. {
  1251. Data = new TSessionData(L"");
  1252. assert(ActiveTerminal != NULL);
  1253. Data->Assign(ActiveTerminal->SessionData);
  1254. UpdateSessionCredentials(Data);
  1255. }
  1256. // putty does not support resolving environment variables in session settings
  1257. Data->ExpandEnvironmentVariables();
  1258. if (ActiveTerminal->TunnelLocalPortNumber != 0)
  1259. {
  1260. Data->ConfigureTunnel(ActiveTerminal->TunnelLocalPortNumber);
  1261. }
  1262. OpenSessionInPutty(GUIConfiguration->PuttyPath, Data);
  1263. }
  1264. __finally
  1265. {
  1266. delete Data;
  1267. }
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. void __fastcall TTerminalManager::NewSession(bool /*FromSite*/, const UnicodeString & SessionUrl)
  1271. {
  1272. UnicodeString DownloadFile; // unused
  1273. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1274. GetLoginData(SessionUrl, NULL, DataList.get(), DownloadFile);
  1275. if (DataList->Count > 0)
  1276. {
  1277. ActiveTerminal = NewTerminals(DataList.get());
  1278. }
  1279. }
  1280. //---------------------------------------------------------------------------
  1281. void __fastcall TTerminalManager::Idle()
  1282. {
  1283. for (int Index = 0; Index < Count; Index++)
  1284. {
  1285. TTerminal * Terminal = Terminals[Index];
  1286. try
  1287. {
  1288. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  1289. assert(ManagedTerminal != NULL);
  1290. // make sure Idle is called on the thread that runs the terminal
  1291. if (ManagedTerminal->TerminalThread != NULL)
  1292. {
  1293. ManagedTerminal->TerminalThread->Idle();
  1294. }
  1295. else
  1296. {
  1297. if (Terminal->Active)
  1298. {
  1299. Terminal->Idle();
  1300. }
  1301. }
  1302. if (Terminal->Active)
  1303. {
  1304. assert(Index < FQueues->Count);
  1305. if (Index < FQueues->Count)
  1306. {
  1307. reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index])->Idle();
  1308. }
  1309. }
  1310. }
  1311. catch(Exception & E)
  1312. {
  1313. if (Terminal == ActiveTerminal)
  1314. {
  1315. // throw further, so that the exception is handled in proper place
  1316. // (particularly in broken-transfer reconnect handler, bug 72)
  1317. throw;
  1318. }
  1319. else
  1320. {
  1321. // we may not have inactive terminal, unless there is a explorer,
  1322. // also Idle is called from explorer anyway
  1323. assert(ScpExplorer != NULL);
  1324. if (ScpExplorer != NULL)
  1325. {
  1326. ScpExplorer->InactiveTerminalException(Terminal, &E);
  1327. }
  1328. if (!Terminal->Active)
  1329. {
  1330. // if session is lost, save the error message and rethrow it
  1331. // once the terminal gets activated
  1332. FTerminationMessages->Strings[Index] = E.Message;
  1333. }
  1334. }
  1335. }
  1336. }
  1337. TTerminalQueue * QueueWithEvent;
  1338. TQueueEvent QueueEvent;
  1339. do
  1340. {
  1341. QueueWithEvent = NULL;
  1342. {
  1343. TGuard Guard(FQueueSection);
  1344. if (!FQueueEvents.empty())
  1345. {
  1346. QueueWithEvent = FQueueEvents[0].first;
  1347. QueueEvent = FQueueEvents[0].second;
  1348. FQueueEvents.erase(FQueueEvents.begin());
  1349. }
  1350. }
  1351. if (QueueWithEvent != NULL)
  1352. {
  1353. int Index = FQueues->IndexOf(QueueWithEvent);
  1354. // the session may not exist anymore
  1355. if (Index >= 0)
  1356. {
  1357. TTerminal * Terminal = Terminals[Index];
  1358. // we can hardly have a queue event without explorer
  1359. assert(ScpExplorer != NULL);
  1360. if (ScpExplorer != NULL)
  1361. {
  1362. ScpExplorer->QueueEvent(Terminal, QueueWithEvent, QueueEvent);
  1363. }
  1364. }
  1365. }
  1366. }
  1367. while (QueueWithEvent != NULL);
  1368. }
  1369. //---------------------------------------------------------------------------
  1370. void __fastcall TTerminalManager::MasterPasswordPrompt()
  1371. {
  1372. if (GetCurrentThreadId() == MainThreadID)
  1373. {
  1374. if (!DoMasterPasswordDialog())
  1375. {
  1376. Abort();
  1377. }
  1378. }
  1379. else
  1380. {
  1381. // this can happen only when we keep cancelling all master password prompts
  1382. // as long as the sessing finally connects (session password has to be
  1383. // explictly typed in), and background transfer is started
  1384. Abort();
  1385. }
  1386. }
  1387. //---------------------------------------------------------------------------
  1388. void __fastcall TTerminalManager::Move(TTerminal * Source, TTerminal * Target)
  1389. {
  1390. FTerminalList->Clear();
  1391. int SourceIndex = IndexOf(Source);
  1392. int TargetIndex = IndexOf(Target);
  1393. TTerminalList::Move(SourceIndex, TargetIndex);
  1394. FQueues->Move(SourceIndex, TargetIndex);
  1395. DoTerminalListChanged();
  1396. // when there are indexed sessions with the same name,
  1397. // the index may change when reordering the sessions
  1398. UpdateAppTitle();
  1399. }
  1400. //---------------------------------------------------------------------------
  1401. void __fastcall TTerminalManager::DoTerminalListChanged()
  1402. {
  1403. if (OnTerminalListChanged)
  1404. {
  1405. OnTerminalListChanged(this);
  1406. }
  1407. }
  1408. //---------------------------------------------------------------------------
  1409. void __fastcall TTerminalManager::SaveWorkspace(TList * DataList)
  1410. {
  1411. for (int Index = 0; Index < Count; Index++)
  1412. {
  1413. TSessionData * Data = Terminals[Index]->SessionData;
  1414. TSessionData * Data2 = new TSessionData(L"");
  1415. DataList->Add(Data2);
  1416. if (StoredSessions->FindSame(Data))
  1417. {
  1418. Data2->Link = Data->Name;
  1419. }
  1420. else
  1421. {
  1422. Data2->Assign(Data);
  1423. }
  1424. Data2->Name = IntToHex(Index, 4);
  1425. Data2->IsWorkspace = true;
  1426. }
  1427. }
  1428. //---------------------------------------------------------------------------
  1429. TTerminal * __fastcall TTerminalManager::FindActiveTerminalForSite(TSessionData * Data)
  1430. {
  1431. TTerminal * Result = NULL;
  1432. for (int Index = 0; (Result == NULL) && (Index < Count); Index++)
  1433. {
  1434. TTerminal * Terminal = Terminals[Index];
  1435. if (Terminal->Active &&
  1436. Terminal->SessionData->IsSameSite(Data))
  1437. {
  1438. Result = Terminal;
  1439. }
  1440. }
  1441. return Result;
  1442. }
  1443. //---------------------------------------------------------------------------
  1444. TTerminalQueue * __fastcall TTerminalManager::FindQueueForTerminal(TTerminal * Terminal)
  1445. {
  1446. int Index = IndexOf(Terminal);
  1447. return reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1448. }