TerminalManager.cpp 45 KB

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