TerminalManager.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  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. try
  435. {
  436. if (ActiveTerminal && (Terminal == ActiveTerminal))
  437. {
  438. if ((Count > 0) && !FDestroying)
  439. {
  440. ActiveTerminal = Terminals[Index < Count ? Index : Index - 1];
  441. }
  442. else
  443. {
  444. ActiveTerminal = NULL;
  445. }
  446. }
  447. else
  448. {
  449. SaveTerminal(Terminal);
  450. }
  451. }
  452. // ActiveTerminal = NULL throws EAbort when Login dialog is closed
  453. __finally
  454. {
  455. // only now all references to/from queue (particularly events to explorer)
  456. // are cleared
  457. delete Queue;
  458. delete Terminal;
  459. DoTerminalListChanged();
  460. }
  461. }
  462. }
  463. //---------------------------------------------------------------------------
  464. void __fastcall TTerminalManager::SetScpExplorer(TCustomScpExplorerForm * value)
  465. {
  466. if (ScpExplorer != value)
  467. {
  468. // changing explorer is not supported yet
  469. DebugAssert(!ScpExplorer || !value);
  470. FScpExplorer = value;
  471. if (FScpExplorer)
  472. {
  473. FScpExplorer->Terminal = ActiveTerminal;
  474. FScpExplorer->Queue = ActiveQueue;
  475. FOnLastTerminalClosed = FScpExplorer->LastTerminalClosed;
  476. FOnTerminalListChanged = FScpExplorer->TerminalListChanged;
  477. UpdateTaskbarList();
  478. }
  479. else
  480. {
  481. FOnLastTerminalClosed = NULL;
  482. FOnTerminalListChanged = NULL;
  483. }
  484. }
  485. }
  486. //---------------------------------------------------------------------------
  487. void __fastcall TTerminalManager::SetActiveTerminal(TTerminal * value)
  488. {
  489. DoSetActiveTerminal(value, false);
  490. }
  491. //---------------------------------------------------------------------------
  492. void __fastcall TTerminalManager::SetActiveTerminalWithAutoReconnect(TTerminal * value)
  493. {
  494. DoSetActiveTerminal(value, true);
  495. }
  496. //---------------------------------------------------------------------------
  497. void __fastcall TTerminalManager::DoSetActiveTerminal(TTerminal * value, bool AutoReconnect)
  498. {
  499. if (ActiveTerminal != value)
  500. {
  501. // here used to be call to TCustomScpExporer::UpdateSessionData (now UpdateTerminal)
  502. // but it seems to be duplicate to call from TCustomScpExporer::TerminalChanging
  503. TTerminal * PActiveTerminal = ActiveTerminal;
  504. FActiveTerminal = value;
  505. // moved from else block of next if (ActiveTerminal) statement
  506. // so ScpExplorer can update its caption
  507. UpdateAppTitle();
  508. if (ScpExplorer)
  509. {
  510. if (ActiveTerminal && (ActiveTerminal->Status == ssOpened))
  511. {
  512. TerminalReady();
  513. }
  514. else
  515. {
  516. ScpExplorer->Terminal = NULL;
  517. ScpExplorer->Queue = NULL;
  518. }
  519. }
  520. if (PActiveTerminal && !PActiveTerminal->Active)
  521. {
  522. SaveTerminal(PActiveTerminal);
  523. }
  524. if (ActiveTerminal)
  525. {
  526. if (!PActiveTerminal)
  527. {
  528. CreateLogMemo();
  529. }
  530. DebugAssert(LogMemo);
  531. LogMemo->SessionLog = ActiveTerminal->Log;
  532. SwitchLogFormSessionLog();
  533. int Index = ActiveTerminalIndex;
  534. if (!ActiveTerminal->Active && !FTerminationMessages->Strings[Index].IsEmpty())
  535. {
  536. UnicodeString Message = FTerminationMessages->Strings[Index];
  537. FTerminationMessages->Strings[Index] = L"";
  538. if (AutoReconnect)
  539. {
  540. ReconnectActiveTerminal();
  541. }
  542. else
  543. {
  544. Exception * E = new ESshFatal(NULL, Message);
  545. try
  546. {
  547. // finally show pending terminal message,
  548. // this gives user also possibility to reconnect
  549. ActiveTerminal->ShowExtendedException(E);
  550. }
  551. __finally
  552. {
  553. delete E;
  554. }
  555. }
  556. }
  557. }
  558. else
  559. {
  560. FreeLogMemo();
  561. if (OnLastTerminalClosed)
  562. {
  563. OnLastTerminalClosed(this);
  564. }
  565. }
  566. if ((ActiveTerminal != NULL) && !ActiveTerminal->Active)
  567. {
  568. ConnectActiveTerminal();
  569. }
  570. }
  571. }
  572. //---------------------------------------------------------------------------
  573. void __fastcall TTerminalManager::QueueStatusUpdated()
  574. {
  575. UpdateAppTitle();
  576. }
  577. //---------------------------------------------------------------------------
  578. void __fastcall TTerminalManager::UpdateAppTitle()
  579. {
  580. if (ScpExplorer)
  581. {
  582. UnicodeString NewTitle;
  583. if (ActiveTerminal)
  584. {
  585. NewTitle = FormatMainFormCaption(ActiveTerminalTitle);
  586. }
  587. else
  588. {
  589. NewTitle = FormatMainFormCaption(L"");
  590. }
  591. UnicodeString QueueProgressTitle;
  592. if (!FForegroundProgressTitle.IsEmpty())
  593. {
  594. NewTitle = FForegroundProgressTitle + L" - " + NewTitle;
  595. }
  596. else if (!FProgressTitle.IsEmpty() && !ForegroundTask())
  597. {
  598. NewTitle = FProgressTitle + L" - " + NewTitle;
  599. }
  600. else if ((ScpExplorer != NULL) && (ScpExplorer->Handle != GetAncestor(GetActiveWindow(), GA_ROOTOWNER)) &&
  601. !(QueueProgressTitle = ScpExplorer->GetQueueProgressTitle()).IsEmpty())
  602. {
  603. NewTitle = QueueProgressTitle + L" - " + NewTitle;
  604. }
  605. else if (ActiveTerminal && (ScpExplorer != NULL))
  606. {
  607. UnicodeString Path = ScpExplorer->PathForCaption();
  608. if (!Path.IsEmpty())
  609. {
  610. NewTitle = Path + L" - " + NewTitle;
  611. }
  612. }
  613. ScpExplorer->Caption = NewTitle;
  614. ScpExplorer->ApplicationTitleChanged();
  615. }
  616. }
  617. //---------------------------------------------------------------------------
  618. void __fastcall TTerminalManager::SaveTerminal(TTerminal * Terminal)
  619. {
  620. TSessionData * Data = StoredSessions->FindSame(Terminal->SessionData);
  621. if (Data != NULL)
  622. {
  623. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  624. DebugAssert(ManagedTerminal != NULL);
  625. bool Changed = false;
  626. if (Terminal->SessionData->UpdateDirectories)
  627. {
  628. Data->CopyDirectoriesStateData(ManagedTerminal->StateData);
  629. Changed = true;
  630. }
  631. if (Changed)
  632. {
  633. // modified only, implicit
  634. StoredSessions->Save(false, false);
  635. }
  636. }
  637. }
  638. //---------------------------------------------------------------------------
  639. void __fastcall TTerminalManager::CreateLogMemo()
  640. {
  641. DebugAssert(!FLogMemo);
  642. DebugAssert(ActiveTerminal);
  643. FLogMemo = new TLogMemo(Application);
  644. try
  645. {
  646. FLogMemo->SessionLog = ActiveTerminal->Log;
  647. FLogMemo->PopupMenu = NonVisualDataModule->LogMemoPopup;
  648. }
  649. catch (...)
  650. {
  651. delete FLogMemo;
  652. throw;
  653. }
  654. }
  655. //---------------------------------------------------------------------------
  656. void __fastcall TTerminalManager::FreeLogMemo()
  657. {
  658. DebugAssert(LogMemo);
  659. LogMemo->PopupMenu = NULL;
  660. SAFE_DESTROY(FLogMemo);
  661. }
  662. //---------------------------------------------------------------------------
  663. void __fastcall TTerminalManager::HandleException(Exception * E)
  664. {
  665. // can be null for example when exception is thrown on login dialog
  666. if (ActiveTerminal != NULL)
  667. {
  668. ActiveTerminal->ShowExtendedException(E);
  669. }
  670. else
  671. {
  672. ShowExtendedException(E);
  673. }
  674. }
  675. //---------------------------------------------------------------------------
  676. void __fastcall TTerminalManager::ApplicationException(TObject * /*Sender*/,
  677. Exception * E)
  678. {
  679. HandleException(E);
  680. }
  681. //---------------------------------------------------------------------------
  682. void __fastcall TTerminalManager::ApplicationShowHint(UnicodeString & HintStr,
  683. bool & /*CanShow*/, THintInfo & HintInfo)
  684. {
  685. HintInfo.HintData = HintInfo.HintControl;
  686. TLabel * HintLabel = dynamic_cast<TLabel *>(HintInfo.HintControl);
  687. if ((HintLabel != NULL) && HasLabelHintPopup(HintLabel, HintStr))
  688. {
  689. // Hack for transfer setting labels.
  690. // Should be converted to something like HintLabel()
  691. HintInfo.HideTimeout = 100000; // "almost" never
  692. }
  693. else if (dynamic_cast<TProgressBar *>(HintInfo.HintControl) != NULL)
  694. {
  695. // Hint is forcibly hidden in TProgressForm::FormHide
  696. HintInfo.HideTimeout = 100000; // "almost" never
  697. HintInfo.ReshowTimeout = 500; // updated each 0.5s
  698. }
  699. else
  700. {
  701. int HintMaxWidth = 300;
  702. TControl * ScaleControl = HintInfo.HintControl;
  703. if (DebugAlwaysFalse(HintInfo.HintControl == NULL) ||
  704. (GetParentForm(HintInfo.HintControl) == NULL))
  705. {
  706. ScaleControl = ScpExplorer;
  707. }
  708. HintMaxWidth = ScaleByTextHeight(ScaleControl, HintMaxWidth);
  709. HintInfo.HintMaxWidth = HintMaxWidth;
  710. }
  711. }
  712. //---------------------------------------------------------------------------
  713. bool __fastcall TTerminalManager::HandleMouseWheel(WPARAM WParam, LPARAM LParam)
  714. {
  715. // WORKAROUND This is no longer necessary on Windows 10
  716. bool Result = false;
  717. if (Application->Active)
  718. {
  719. TPoint Point(LOWORD(LParam), HIWORD(LParam));
  720. TWinControl * Control = FindVCLWindow(Point);
  721. if (Control != NULL)
  722. {
  723. TCustomForm * Form = GetParentForm(Control);
  724. // Only case we expect the parent form to be NULL is on the Find/Replace dialog,
  725. // which is owned by VCL's internal TRedirectorWindow.
  726. DebugAssert((Form != NULL) || (Control->ClassName() == L"TRedirectorWindow"));
  727. if ((Form != NULL) && Form->Active)
  728. {
  729. // Send it only to windows we tested it with.
  730. // Though we should sooner or later remove this test and pass it to all our windows.
  731. if (Form->Perform(WM_WANTS_MOUSEWHEEL, 0, 0) == 1)
  732. {
  733. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  734. Result = true;
  735. }
  736. }
  737. }
  738. }
  739. return Result;
  740. }
  741. //---------------------------------------------------------------------------
  742. void __fastcall TTerminalManager::ApplicationMessage(TMsg & Msg, bool & Handled)
  743. {
  744. if (Msg.message == FTaskbarButtonCreatedMessage)
  745. {
  746. CreateTaskbarList();
  747. }
  748. if (Msg.message == WM_MOUSEWHEEL)
  749. {
  750. Handled = HandleMouseWheel(Msg.wParam, Msg.lParam);
  751. }
  752. }
  753. //---------------------------------------------------------------------------
  754. void __fastcall TTerminalManager::ApplicationModalBegin(TObject * /*Sender*/)
  755. {
  756. NonVisualDataModule->StartBusy();
  757. if (ScpExplorer != NULL)
  758. {
  759. ScpExplorer->SuspendWindowLock();
  760. }
  761. }
  762. //---------------------------------------------------------------------------
  763. void __fastcall TTerminalManager::ApplicationModalEnd(TObject * /*Sender*/)
  764. {
  765. NonVisualDataModule->EndBusy();
  766. if (ScpExplorer != NULL)
  767. {
  768. ScpExplorer->ResumeWindowLock();
  769. }
  770. }
  771. //---------------------------------------------------------------------------
  772. void __fastcall TTerminalManager::InitTaskbarButtonCreatedMessage()
  773. {
  774. // XE6 VCL already handles TaskbarButtonCreated, but does not call ChangeWindowMessageFilterEx.
  775. // So we keep our implementation.
  776. // See also http://stackoverflow.com/a/14618587/850848
  777. FTaskbarButtonCreatedMessage = RegisterWindowMessage(L"TaskbarButtonCreated");
  778. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  779. ChangeWindowMessageFilterExProc ChangeWindowMessageFilterEx =
  780. (ChangeWindowMessageFilterExProc)GetProcAddress(User32Library, "ChangeWindowMessageFilterEx");
  781. if (ChangeWindowMessageFilterEx != NULL)
  782. {
  783. // without this we won't get TaskbarButtonCreated, when app is running elevated
  784. ChangeWindowMessageFilterEx(
  785. Application->Handle, FTaskbarButtonCreatedMessage, MSGFLT_ALLOW, NULL);
  786. }
  787. }
  788. //---------------------------------------------------------------------------
  789. void __fastcall TTerminalManager::CreateTaskbarList()
  790. {
  791. ReleaseTaskbarList();
  792. if(SUCCEEDED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL,
  793. IID_ITaskbarList3, (void **) &FTaskbarList)))
  794. {
  795. if (ScpExplorer != NULL)
  796. {
  797. UpdateTaskbarList();
  798. }
  799. }
  800. }
  801. //---------------------------------------------------------------------------
  802. void __fastcall TTerminalManager::ReleaseTaskbarList()
  803. {
  804. if (FTaskbarList != NULL)
  805. {
  806. FTaskbarList->Release();
  807. }
  808. }
  809. //---------------------------------------------------------------------------
  810. void __fastcall TTerminalManager::UpdateTaskbarList()
  811. {
  812. ScpExplorer->UpdateTaskbarList(FTaskbarList);
  813. }
  814. //---------------------------------------------------------------------------
  815. void __fastcall TTerminalManager::DeleteLocalFile(const UnicodeString FileName, bool Alternative)
  816. {
  817. RecursiveDeleteFileChecked(FileName, (WinConfiguration->DeleteToRecycleBin != Alternative));
  818. }
  819. //---------------------------------------------------------------------------
  820. void __fastcall TTerminalManager::TerminalQueryUser(TObject * Sender,
  821. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  822. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * /*Arg*/)
  823. {
  824. UnicodeString HelpKeyword;
  825. TMessageParams MessageParams(Params);
  826. UnicodeString AQuery = Query;
  827. if (Params != NULL)
  828. {
  829. HelpKeyword = Params->HelpKeyword;
  830. if (FLAGSET(Params->Params, qpFatalAbort))
  831. {
  832. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  833. if (!MessageParams.TimerMessage.IsEmpty())
  834. {
  835. MessageParams.TimerMessage = FMTLOAD(WARN_FATAL_ERROR, (MessageParams.TimerMessage));
  836. }
  837. }
  838. }
  839. if (ScpExplorer)
  840. {
  841. Answer = ScpExplorer->MoreMessageDialog(AQuery, MoreMessages, Type, Answers,
  842. HelpKeyword, &MessageParams, dynamic_cast<TTerminal *>(Sender));
  843. }
  844. else
  845. {
  846. Answer = MoreMessageDialog(AQuery, MoreMessages, Type, Answers, HelpKeyword,
  847. &MessageParams);
  848. }
  849. }
  850. //---------------------------------------------------------------------------
  851. void __fastcall TTerminalManager::AuthenticateFormCancel(TObject * Sender)
  852. {
  853. TAuthenticateForm * Form = dynamic_cast<TAuthenticateForm *>(Sender);
  854. DebugAssert(Form != NULL);
  855. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Form->Terminal);
  856. // will be null e.g. for background transfers
  857. if (ManagedTerminal != NULL)
  858. {
  859. TTerminalThread * TerminalThread = ManagedTerminal->TerminalThread;
  860. // can be NULL for reconnects from transfers
  861. if ((TerminalThread != NULL) && !TerminalThread->Cancelling)
  862. {
  863. Form->Log(LoadStr(AUTH_CANCELLING));
  864. TerminalThread->Cancel();
  865. }
  866. }
  867. FAuthenticationCancelled = true;
  868. }
  869. //---------------------------------------------------------------------------
  870. TAuthenticateForm * __fastcall TTerminalManager::MakeAuthenticateForm(
  871. TTerminal * Terminal)
  872. {
  873. TAuthenticateForm * Dialog = SafeFormCreate<TAuthenticateForm>();
  874. Dialog->Init(Terminal);
  875. DebugAssert(Dialog->OnCancel == NULL);
  876. Dialog->OnCancel = AuthenticateFormCancel;
  877. return Dialog;
  878. }
  879. //---------------------------------------------------------------------------
  880. void __fastcall TTerminalManager::FileNameInputDialogInitializeRenameBaseName(
  881. TObject * /*Sender*/, TInputDialogData * Data)
  882. {
  883. EditSelectBaseName(Data->Edit->Handle);
  884. }
  885. //---------------------------------------------------------------------------
  886. void __fastcall TTerminalManager::TerminalPromptUser(
  887. TTerminal * Terminal, TPromptKind Kind, UnicodeString Name, UnicodeString Instructions,
  888. TStrings * Prompts, TStrings * Results, bool & Result, void * /*Arg*/)
  889. {
  890. if (((Kind == pkPrompt) || (Kind == pkFileName)) && (FAuthenticateForm == NULL) &&
  891. (Terminal->Status != ssOpening))
  892. {
  893. DebugAssert(Instructions.IsEmpty());
  894. DebugAssert(Prompts->Count == 1);
  895. DebugAssert(FLAGSET(int(Prompts->Objects[0]), pupEcho));
  896. UnicodeString AResult = Results->Strings[0];
  897. TInputDialogInitialize InputDialogInitialize = NULL;
  898. if ((Kind == pkFileName) && !WinConfiguration->RenameWholeName)
  899. {
  900. InputDialogInitialize = FileNameInputDialogInitializeRenameBaseName;
  901. }
  902. Result = InputDialog(Name, Prompts->Strings[0], AResult, L"", NULL, false, InputDialogInitialize);
  903. if (Result)
  904. {
  905. Results->Strings[0] = AResult;
  906. }
  907. }
  908. else
  909. {
  910. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  911. if (AuthenticateForm == NULL)
  912. {
  913. AuthenticateForm = MakeAuthenticateForm(Terminal);
  914. }
  915. try
  916. {
  917. Result = AuthenticateForm->PromptUser(Kind, Name, Instructions, Prompts, Results,
  918. (FAuthenticateForm != NULL), Terminal->StoredCredentialsTried);
  919. }
  920. __finally
  921. {
  922. if (FAuthenticateForm == NULL)
  923. {
  924. delete AuthenticateForm;
  925. }
  926. }
  927. }
  928. }
  929. //---------------------------------------------------------------------------
  930. void __fastcall TTerminalManager::TerminalDisplayBanner(
  931. TTerminal * Terminal, UnicodeString SessionName,
  932. const UnicodeString & Banner, bool & NeverShowAgain, int Options)
  933. {
  934. DebugAssert(FAuthenticateForm != NULL);
  935. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  936. if (AuthenticateForm == NULL)
  937. {
  938. AuthenticateForm = MakeAuthenticateForm(Terminal);
  939. }
  940. try
  941. {
  942. AuthenticateForm->Banner(Banner, NeverShowAgain, Options);
  943. }
  944. __finally
  945. {
  946. if (FAuthenticateForm == NULL)
  947. {
  948. delete AuthenticateForm;
  949. }
  950. }
  951. }
  952. //---------------------------------------------------------------------------
  953. void __fastcall TTerminalManager::TerminalShowExtendedException(
  954. TTerminal * Terminal, Exception * E, void * /*Arg*/)
  955. {
  956. if (ScpExplorer)
  957. {
  958. ScpExplorer->ShowExtendedException(Terminal, E);
  959. }
  960. else
  961. {
  962. ShowExtendedExceptionEx(Terminal, E);
  963. }
  964. }
  965. //---------------------------------------------------------------------------
  966. static TDateTime DirectoryReadingProgressDelay(0, 0, 1, 500);
  967. //---------------------------------------------------------------------------
  968. void __fastcall TTerminalManager::TerminalReadDirectoryProgress(
  969. TObject * /*Sender*/, int Progress, int ResolvedLinks, bool & Cancel)
  970. {
  971. if (Progress == 0)
  972. {
  973. if (ScpExplorer != NULL)
  974. {
  975. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  976. ScpExplorer->LockWindow();
  977. }
  978. FDirectoryReadingStart = Now();
  979. if (!FProgressTitle.IsEmpty() || !FForegroundProgressTitle.IsEmpty())
  980. {
  981. FProgressTitle = L"";
  982. FForegroundProgressTitle = L"";
  983. UpdateAppTitle();
  984. }
  985. // Reset "was ESC ever pressed?" state
  986. GetAsyncKeyState(VK_ESCAPE);
  987. }
  988. else if (Progress < 0)
  989. {
  990. if (Progress == -2)
  991. {
  992. // cancelled
  993. if (ScpExplorer != NULL)
  994. {
  995. ScpExplorer->ReadDirectoryCancelled();
  996. }
  997. }
  998. else
  999. {
  1000. if (ScpExplorer != NULL)
  1001. {
  1002. ScpExplorer->UnlockWindow();
  1003. }
  1004. FProgressTitle = L"";
  1005. FForegroundProgressTitle = L"";
  1006. UpdateAppTitle();
  1007. }
  1008. }
  1009. else
  1010. {
  1011. // If the least significant bit is set,
  1012. // the key was pressed after the previous call to GetAsyncKeyState.
  1013. int KeyState = GetAsyncKeyState(VK_ESCAPE);
  1014. if (FLAGSET(KeyState, 0x01))
  1015. {
  1016. Cancel = true;
  1017. }
  1018. if ((Now() - FDirectoryReadingStart) >= DirectoryReadingProgressDelay)
  1019. {
  1020. // 4 is arbitrary number
  1021. FForegroundProgressTitle =
  1022. FMTLOAD(ResolvedLinks >= 4 ? DIRECTORY_READING_AND_RESOLVING_PROGRESS : DIRECTORY_READING_PROGRESS,
  1023. (Progress));
  1024. UpdateAppTitle();
  1025. }
  1026. }
  1027. }
  1028. //---------------------------------------------------------------------------
  1029. void __fastcall TTerminalManager::TerminalInformation(
  1030. TTerminal * Terminal, const UnicodeString & Str, bool /*Status*/, int Phase)
  1031. {
  1032. if (Phase == 1)
  1033. {
  1034. if (FAuthenticating == 0)
  1035. {
  1036. FBusyToken = BusyStart();
  1037. }
  1038. FAuthenticating++;
  1039. }
  1040. else if (Phase == 0)
  1041. {
  1042. DebugAssert(FAuthenticating > 0);
  1043. FAuthenticating--;
  1044. if (FAuthenticating == 0)
  1045. {
  1046. BusyEnd(FBusyToken);
  1047. FBusyToken = NULL;
  1048. }
  1049. SAFE_DESTROY(FAuthenticateForm);
  1050. }
  1051. else
  1052. {
  1053. if (FAuthenticating > 0)
  1054. {
  1055. bool ShowPending = false;
  1056. if (FAuthenticateForm == NULL)
  1057. {
  1058. FAuthenticateForm = MakeAuthenticateForm(Terminal);
  1059. ShowPending = true;
  1060. }
  1061. FAuthenticateForm->Log(Str);
  1062. if (ShowPending)
  1063. {
  1064. FAuthenticateForm->ShowAsModal();
  1065. }
  1066. }
  1067. }
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. void __fastcall TTerminalManager::OperationFinished(::TFileOperation Operation,
  1071. TOperationSide Side, bool Temp, const UnicodeString & FileName, bool Success,
  1072. TOnceDoneOperation & OnceDoneOperation)
  1073. {
  1074. DebugAssert(ScpExplorer);
  1075. ScpExplorer->OperationFinished(Operation, Side, Temp, FileName, Success,
  1076. OnceDoneOperation);
  1077. }
  1078. //---------------------------------------------------------------------------
  1079. void __fastcall TTerminalManager::OperationProgress(
  1080. TFileOperationProgressType & ProgressData)
  1081. {
  1082. if (ProgressData.InProgress)
  1083. {
  1084. FProgressTitle = TProgressForm::ProgressStr(&ProgressData);
  1085. }
  1086. else
  1087. {
  1088. FProgressTitle = L"";
  1089. }
  1090. UpdateAppTitle();
  1091. DebugAssert(ScpExplorer);
  1092. ScpExplorer->OperationProgress(ProgressData);
  1093. }
  1094. //---------------------------------------------------------------------------
  1095. void __fastcall TTerminalManager::QueueEvent(TTerminalQueue * Queue, TQueueEvent Event)
  1096. {
  1097. TGuard Guard(FQueueSection);
  1098. FQueueEvents.push_back(std::make_pair(Queue, Event));
  1099. }
  1100. //---------------------------------------------------------------------------
  1101. void __fastcall TTerminalManager::ConfigurationChange(TObject * /*Sender*/)
  1102. {
  1103. DebugAssert(Configuration);
  1104. DebugAssert(Configuration == WinConfiguration);
  1105. TTerminalQueue * Queue;
  1106. for (int Index = 0; Index < Count; Index++)
  1107. {
  1108. DebugAssert(Terminals[Index]->Log);
  1109. Terminals[Index]->Log->ReflectSettings();
  1110. Terminals[Index]->ActionLog->ReflectSettings();
  1111. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1112. SetQueueConfiguration(Queue);
  1113. }
  1114. if (ScpExplorer)
  1115. {
  1116. ScpExplorer->ConfigurationChanged();
  1117. }
  1118. }
  1119. //---------------------------------------------------------------------------
  1120. void __fastcall TTerminalManager::TerminalReady()
  1121. {
  1122. ScpExplorer->Terminal = ActiveTerminal;
  1123. ScpExplorer->Queue = ActiveQueue;
  1124. ScpExplorer->TerminalReady();
  1125. }
  1126. //---------------------------------------------------------------------------
  1127. TStrings * __fastcall TTerminalManager::GetTerminalList()
  1128. {
  1129. if (FTerminalList->Count != Count)
  1130. {
  1131. for (int i = 0; i < Count; i++)
  1132. {
  1133. UnicodeString NameN;
  1134. UnicodeString Name = Terminals[i]->SessionData->SessionName;
  1135. int Number = 1;
  1136. NameN = Name;
  1137. while (FTerminalList->IndexOf(NameN) >= 0)
  1138. {
  1139. Number++;
  1140. NameN = FORMAT(L"%s (%d)", (Name, Number));
  1141. }
  1142. if (Number > 1)
  1143. {
  1144. Name = FORMAT(L"%s (%d)", (Name, Number));
  1145. }
  1146. FTerminalList->AddObject(Name, Terminals[i]);
  1147. }
  1148. }
  1149. return FTerminalList;
  1150. }
  1151. //---------------------------------------------------------------------------
  1152. int __fastcall TTerminalManager::GetActiveTerminalIndex()
  1153. {
  1154. return ActiveTerminal ? IndexOf(ActiveTerminal) : -1;
  1155. }
  1156. //---------------------------------------------------------------------------
  1157. void __fastcall TTerminalManager::SetActiveTerminalIndex(int value)
  1158. {
  1159. ActiveTerminal = Terminals[value];
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. UnicodeString __fastcall TTerminalManager::TerminalTitle(TTerminal * Terminal)
  1163. {
  1164. int Index = IndexOf(Terminal);
  1165. UnicodeString Result;
  1166. if (Index >= 0)
  1167. {
  1168. Result = TerminalList->Strings[Index];
  1169. }
  1170. else
  1171. {
  1172. // this is the case of background transfer sessions
  1173. Result = Terminal->SessionData->SessionName;
  1174. }
  1175. return Result;
  1176. }
  1177. //---------------------------------------------------------------------------
  1178. UnicodeString __fastcall TTerminalManager::GetActiveTerminalTitle()
  1179. {
  1180. UnicodeString Result = ActiveTerminal ?
  1181. TerminalTitle(ActiveTerminal) : UnicodeString(L"");
  1182. return Result;
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. TTerminalQueue * __fastcall TTerminalManager::GetActiveQueue()
  1186. {
  1187. TTerminalQueue * Result = NULL;
  1188. if (ActiveTerminal != NULL)
  1189. {
  1190. Result = reinterpret_cast<TTerminalQueue *>(FQueues->Items[ActiveTerminalIndex]);
  1191. }
  1192. return Result;
  1193. }
  1194. //---------------------------------------------------------------------------
  1195. void __fastcall TTerminalManager::CycleTerminals(bool Forward)
  1196. {
  1197. int Index = ActiveTerminalIndex;
  1198. Index += Forward ? 1 : -1;
  1199. if (Index < 0)
  1200. {
  1201. Index = Count-1;
  1202. }
  1203. else if (Index >= Count)
  1204. {
  1205. Index = 0;
  1206. }
  1207. ActiveTerminalIndex = Index;
  1208. }
  1209. //---------------------------------------------------------------------------
  1210. bool __fastcall TTerminalManager::CanOpenInPutty()
  1211. {
  1212. return (ActiveTerminal != NULL) && !GUIConfiguration->PuttyPath.Trim().IsEmpty();
  1213. }
  1214. //---------------------------------------------------------------------------
  1215. void __fastcall TTerminalManager::UpdateSessionCredentials(TSessionData * Data)
  1216. {
  1217. Data->UserName = ActiveTerminal->UserName;
  1218. Data->Password = ActiveTerminal->Password;
  1219. }
  1220. //---------------------------------------------------------------------------
  1221. void __fastcall TTerminalManager::OpenInPutty()
  1222. {
  1223. Configuration->Usage->Inc(L"OpenInPutty");
  1224. TSessionData * Data = NULL;
  1225. try
  1226. {
  1227. // Is NULL on the first session when called from ConnectActiveTerminal()
  1228. // due to WinConfiguration->AutoOpenInPutty
  1229. if (ScpExplorer != NULL)
  1230. {
  1231. Data = ScpExplorer->CloneCurrentSessionData();
  1232. }
  1233. else
  1234. {
  1235. Data = new TSessionData(L"");
  1236. DebugAssert(ActiveTerminal != NULL);
  1237. Data->Assign(ActiveTerminal->SessionData);
  1238. UpdateSessionCredentials(Data);
  1239. }
  1240. // putty does not support resolving environment variables in session settings
  1241. Data->ExpandEnvironmentVariables();
  1242. if (ActiveTerminal->TunnelLocalPortNumber != 0)
  1243. {
  1244. Data->ConfigureTunnel(ActiveTerminal->TunnelLocalPortNumber);
  1245. }
  1246. OpenSessionInPutty(GUIConfiguration->PuttyPath, Data);
  1247. }
  1248. __finally
  1249. {
  1250. delete Data;
  1251. }
  1252. }
  1253. //---------------------------------------------------------------------------
  1254. void __fastcall TTerminalManager::NewSession(bool /*FromSite*/, const UnicodeString & SessionUrl, bool ReloadSessions)
  1255. {
  1256. if (ReloadSessions)
  1257. {
  1258. StoredSessions->Load();
  1259. }
  1260. UnicodeString DownloadFile; // unused
  1261. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1262. GetLoginData(SessionUrl, NULL, DataList.get(), DownloadFile, true);
  1263. if (DataList->Count > 0)
  1264. {
  1265. ActiveTerminal = NewTerminals(DataList.get());
  1266. }
  1267. }
  1268. //---------------------------------------------------------------------------
  1269. void __fastcall TTerminalManager::Idle()
  1270. {
  1271. for (int Index = 0; Index < Count; Index++)
  1272. {
  1273. TTerminal * Terminal = Terminals[Index];
  1274. try
  1275. {
  1276. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  1277. DebugAssert(ManagedTerminal != NULL);
  1278. // make sure Idle is called on the thread that runs the terminal
  1279. if (ManagedTerminal->TerminalThread != NULL)
  1280. {
  1281. ManagedTerminal->TerminalThread->Idle();
  1282. }
  1283. else
  1284. {
  1285. if (Terminal->Active)
  1286. {
  1287. Terminal->Idle();
  1288. }
  1289. }
  1290. if (Terminal->Active)
  1291. {
  1292. DebugAssert(Index < FQueues->Count);
  1293. if (Index < FQueues->Count)
  1294. {
  1295. reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index])->Idle();
  1296. }
  1297. }
  1298. }
  1299. catch(Exception & E)
  1300. {
  1301. if (Terminal == ActiveTerminal)
  1302. {
  1303. // throw further, so that the exception is handled in proper place
  1304. // (particularly in broken-transfer reconnect handler, bug 72)
  1305. throw;
  1306. }
  1307. else
  1308. {
  1309. // we may not have inactive terminal, unless there is a explorer,
  1310. // also Idle is called from explorer anyway
  1311. DebugAssert(ScpExplorer != NULL);
  1312. if (ScpExplorer != NULL)
  1313. {
  1314. ScpExplorer->InactiveTerminalException(Terminal, &E);
  1315. }
  1316. if (!Terminal->Active)
  1317. {
  1318. // if session is lost, save the error message and rethrow it
  1319. // once the terminal gets activated
  1320. FTerminationMessages->Strings[Index] = E.Message;
  1321. }
  1322. }
  1323. }
  1324. }
  1325. TTerminalQueue * QueueWithEvent;
  1326. TQueueEvent QueueEvent;
  1327. do
  1328. {
  1329. QueueWithEvent = NULL;
  1330. {
  1331. TGuard Guard(FQueueSection);
  1332. if (!FQueueEvents.empty())
  1333. {
  1334. QueueWithEvent = FQueueEvents[0].first;
  1335. QueueEvent = FQueueEvents[0].second;
  1336. FQueueEvents.erase(FQueueEvents.begin());
  1337. }
  1338. }
  1339. if (QueueWithEvent != NULL)
  1340. {
  1341. int Index = FQueues->IndexOf(QueueWithEvent);
  1342. // the session may not exist anymore
  1343. if (Index >= 0)
  1344. {
  1345. TTerminal * Terminal = Terminals[Index];
  1346. // we can hardly have a queue event without explorer
  1347. DebugAssert(ScpExplorer != NULL);
  1348. if (ScpExplorer != NULL)
  1349. {
  1350. ScpExplorer->QueueEvent(Terminal, QueueWithEvent, QueueEvent);
  1351. }
  1352. }
  1353. }
  1354. }
  1355. while (QueueWithEvent != NULL);
  1356. }
  1357. //---------------------------------------------------------------------------
  1358. void __fastcall TTerminalManager::MasterPasswordPrompt()
  1359. {
  1360. if (GetCurrentThreadId() == MainThreadID)
  1361. {
  1362. if (!DoMasterPasswordDialog())
  1363. {
  1364. Abort();
  1365. }
  1366. }
  1367. else
  1368. {
  1369. // this can happen only when we keep cancelling all master password prompts
  1370. // as long as the sessing finally connects (session password has to be
  1371. // explictly typed in), and background transfer is started
  1372. Abort();
  1373. }
  1374. }
  1375. //---------------------------------------------------------------------------
  1376. void __fastcall TTerminalManager::Move(TTerminal * Source, TTerminal * Target)
  1377. {
  1378. FTerminalList->Clear();
  1379. int SourceIndex = IndexOf(Source);
  1380. int TargetIndex = IndexOf(Target);
  1381. TTerminalList::Move(SourceIndex, TargetIndex);
  1382. FQueues->Move(SourceIndex, TargetIndex);
  1383. DoTerminalListChanged();
  1384. // when there are indexed sessions with the same name,
  1385. // the index may change when reordering the sessions
  1386. UpdateAppTitle();
  1387. }
  1388. //---------------------------------------------------------------------------
  1389. void __fastcall TTerminalManager::DoTerminalListChanged()
  1390. {
  1391. if (OnTerminalListChanged)
  1392. {
  1393. OnTerminalListChanged(this);
  1394. }
  1395. }
  1396. //---------------------------------------------------------------------------
  1397. void __fastcall TTerminalManager::SaveWorkspace(TList * DataList)
  1398. {
  1399. for (int Index = 0; Index < Count; Index++)
  1400. {
  1401. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminals[Index]);
  1402. TSessionData * Data = StoredSessions->SaveWorkspaceData(ManagedTerminal->StateData);
  1403. DataList->Add(Data);
  1404. Data->Name = IntToHex(Index, 4);
  1405. }
  1406. }
  1407. //---------------------------------------------------------------------------
  1408. TTerminal * __fastcall TTerminalManager::FindActiveTerminalForSite(TSessionData * Data)
  1409. {
  1410. TTerminal * Result = NULL;
  1411. for (int Index = 0; (Result == NULL) && (Index < Count); Index++)
  1412. {
  1413. TTerminal * Terminal = Terminals[Index];
  1414. if (Terminal->Active &&
  1415. Terminal->SessionData->IsSameSite(Data))
  1416. {
  1417. Result = Terminal;
  1418. }
  1419. }
  1420. return Result;
  1421. }
  1422. //---------------------------------------------------------------------------
  1423. TTerminalQueue * __fastcall TTerminalManager::FindQueueForTerminal(TTerminal * Terminal)
  1424. {
  1425. int Index = IndexOf(Terminal);
  1426. return reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1427. }