TerminalManager.cpp 47 KB

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