TerminalManager.cpp 47 KB

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