TerminalManager.cpp 47 KB

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