1
0

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