TerminalManager.cpp 45 KB

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