TerminalManager.cpp 45 KB

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