TerminalManager.cpp 46 KB

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