TerminalManager.cpp 45 KB

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