TerminalManager.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  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. DebugAssert(Application && !Application->OnException);
  75. Application->OnException = ApplicationException;
  76. DebugAssert(Application->OnShowHint == NULL);
  77. Application->OnShowHint = ApplicationShowHint;
  78. DebugAssert(Application->OnMessage == NULL);
  79. Application->OnMessage = ApplicationMessage;
  80. DebugAssert(Application->OnModalBegin == NULL);
  81. Application->OnModalBegin = ApplicationModalBegin;
  82. DebugAssert(Application->OnModalEnd == NULL);
  83. Application->OnModalEnd = ApplicationModalEnd;
  84. DebugAssert(WinConfiguration->OnMasterPasswordPrompt == NULL);
  85. WinConfiguration->OnMasterPasswordPrompt = MasterPasswordPrompt;
  86. InitTaskbarButtonCreatedMessage();
  87. DebugAssert(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. DebugAssert(!ScpExplorer);
  100. DebugAssert(Configuration->OnChange == ConfigurationChange);
  101. Configuration->OnChange = NULL;
  102. DebugAssert(Application && (Application->OnException == ApplicationException));
  103. Application->OnException = NULL;
  104. DebugAssert(Application->OnShowHint == ApplicationShowHint);
  105. Application->OnShowHint = ApplicationShowHint;
  106. DebugAssert(Application->OnMessage == ApplicationMessage);
  107. Application->OnMessage = NULL;
  108. DebugAssert(Application->OnModalBegin == ApplicationModalBegin);
  109. Application->OnModalBegin = NULL;
  110. DebugAssert(Application->OnModalEnd == ApplicationModalEnd);
  111. Application->OnModalEnd = NULL;
  112. DebugAssert(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. DebugAssert(ActiveTerminal);
  203. FreeTerminal(ActiveTerminal);
  204. }
  205. else
  206. {
  207. DebugAssert(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. DebugAssert((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. DebugAssert(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. DebugAssert(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. DebugAssert(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. DebugAssert(FTerminalPendingAction == tpNull);
  316. FTerminalPendingAction = ::tpNone;
  317. try
  318. {
  319. DebugAssert(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. DebugAssert(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. DebugAssert(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. DebugAssert(!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. DebugAssert(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. DebugAssert(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. DebugAssert(!FLogMemo);
  672. DebugAssert(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. DebugAssert(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. int HintMaxWidth = 300;
  733. TControl * ScaleControl = HintInfo.HintControl;
  734. if (DebugAlwaysFalse(HintInfo.HintControl == NULL) ||
  735. (GetParentForm(HintInfo.HintControl) == NULL))
  736. {
  737. ScaleControl = ScpExplorer;
  738. }
  739. HintMaxWidth = ScaleByTextHeight(ScaleControl, HintMaxWidth);
  740. HintInfo.HintMaxWidth = HintMaxWidth;
  741. }
  742. }
  743. //---------------------------------------------------------------------------
  744. bool __fastcall TTerminalManager::HandleMouseWheel(WPARAM WParam, LPARAM LParam)
  745. {
  746. bool Result = false;
  747. if (Application->Active)
  748. {
  749. TPoint Point(LOWORD(LParam), HIWORD(LParam));
  750. TWinControl * Control = FindVCLWindow(Point);
  751. if (Control != NULL)
  752. {
  753. TCustomForm * Form = GetParentForm(Control);
  754. // Only case we expect the parent form to be NULL is on the Find/Replace dialog,
  755. // which is owned by VCL's internal TRedirectorWindow.
  756. DebugAssert((Form != NULL) || (Control->ClassName() == L"TRedirectorWindow"));
  757. if ((Form != NULL) && Form->Active)
  758. {
  759. // Send it only to windows we tested it with.
  760. // Though we should sooner or later remote this test and pass it to all our windows.
  761. if (Form->Perform(WM_WANTS_MOUSEWHEEL, 0, 0) == 1)
  762. {
  763. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  764. Result = true;
  765. }
  766. }
  767. }
  768. }
  769. return Result;
  770. }
  771. //---------------------------------------------------------------------------
  772. void __fastcall TTerminalManager::ApplicationMessage(TMsg & Msg, bool & Handled)
  773. {
  774. if (Msg.message == FTaskbarButtonCreatedMessage)
  775. {
  776. CreateTaskbarList();
  777. }
  778. if (Msg.message == WM_MOUSEWHEEL)
  779. {
  780. Handled = HandleMouseWheel(Msg.wParam, Msg.lParam);
  781. }
  782. }
  783. //---------------------------------------------------------------------------
  784. void __fastcall TTerminalManager::ApplicationModalBegin(TObject * /*Sender*/)
  785. {
  786. NonVisualDataModule->StartBusy();
  787. if (ScpExplorer != NULL)
  788. {
  789. ScpExplorer->SuspendWindowLock();
  790. }
  791. }
  792. //---------------------------------------------------------------------------
  793. void __fastcall TTerminalManager::ApplicationModalEnd(TObject * /*Sender*/)
  794. {
  795. NonVisualDataModule->EndBusy();
  796. if (ScpExplorer != NULL)
  797. {
  798. ScpExplorer->ResumeWindowLock();
  799. }
  800. }
  801. //---------------------------------------------------------------------------
  802. void __fastcall TTerminalManager::InitTaskbarButtonCreatedMessage()
  803. {
  804. // XE6 VCL already handles TaskbarButtonCreated, but does not call ChangeWindowMessageFilterEx.
  805. // So we keep our implementation.
  806. // See also http://stackoverflow.com/a/14618587/850848
  807. FTaskbarButtonCreatedMessage = RegisterWindowMessage(L"TaskbarButtonCreated");
  808. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  809. ChangeWindowMessageFilterExProc ChangeWindowMessageFilterEx =
  810. (ChangeWindowMessageFilterExProc)GetProcAddress(User32Library, "ChangeWindowMessageFilterEx");
  811. if (ChangeWindowMessageFilterEx != NULL)
  812. {
  813. // without this we won't get TaskbarButtonCreated, when app is running elevated
  814. ChangeWindowMessageFilterEx(
  815. Application->Handle, FTaskbarButtonCreatedMessage, MSGFLT_ALLOW, NULL);
  816. }
  817. }
  818. //---------------------------------------------------------------------------
  819. void __fastcall TTerminalManager::CreateTaskbarList()
  820. {
  821. ReleaseTaskbarList();
  822. if(SUCCEEDED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL,
  823. IID_ITaskbarList3, (void **) &FTaskbarList)))
  824. {
  825. if (ScpExplorer != NULL)
  826. {
  827. UpdateTaskbarList();
  828. }
  829. }
  830. }
  831. //---------------------------------------------------------------------------
  832. void __fastcall TTerminalManager::ReleaseTaskbarList()
  833. {
  834. if (FTaskbarList != NULL)
  835. {
  836. FTaskbarList->Release();
  837. }
  838. }
  839. //---------------------------------------------------------------------------
  840. void __fastcall TTerminalManager::UpdateTaskbarList()
  841. {
  842. ScpExplorer->UpdateTaskbarList(FTaskbarList);
  843. }
  844. //---------------------------------------------------------------------------
  845. void __fastcall TTerminalManager::DeleteLocalFile(const UnicodeString FileName, bool Alternative)
  846. {
  847. RecursiveDeleteFileChecked(FileName, (WinConfiguration->DeleteToRecycleBin != Alternative));
  848. }
  849. //---------------------------------------------------------------------------
  850. void __fastcall TTerminalManager::TerminalQueryUser(TObject * Sender,
  851. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  852. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * /*Arg*/)
  853. {
  854. UnicodeString HelpKeyword;
  855. TMessageParams MessageParams(Params);
  856. UnicodeString AQuery = Query;
  857. if (Params != NULL)
  858. {
  859. HelpKeyword = Params->HelpKeyword;
  860. if (FLAGSET(Params->Params, qpFatalAbort))
  861. {
  862. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  863. if (!MessageParams.TimerMessage.IsEmpty())
  864. {
  865. MessageParams.TimerMessage = FMTLOAD(WARN_FATAL_ERROR, (MessageParams.TimerMessage));
  866. }
  867. }
  868. }
  869. if (ScpExplorer)
  870. {
  871. Answer = ScpExplorer->MoreMessageDialog(AQuery, MoreMessages, Type, Answers,
  872. HelpKeyword, &MessageParams, dynamic_cast<TTerminal *>(Sender));
  873. }
  874. else
  875. {
  876. Answer = MoreMessageDialog(AQuery, MoreMessages, Type, Answers, HelpKeyword,
  877. &MessageParams);
  878. }
  879. }
  880. //---------------------------------------------------------------------------
  881. void __fastcall TTerminalManager::AuthenticateFormCancel(TObject * Sender)
  882. {
  883. TAuthenticateForm * Form = dynamic_cast<TAuthenticateForm *>(Sender);
  884. DebugAssert(Form != NULL);
  885. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Form->Terminal);
  886. // will be null e.g. for background transfers
  887. if (ManagedTerminal != NULL)
  888. {
  889. TTerminalThread * TerminalThread = ManagedTerminal->TerminalThread;
  890. // can be NULL for reconnects from transfers
  891. if ((TerminalThread != NULL) && !TerminalThread->Cancelling)
  892. {
  893. Form->Log(LoadStr(AUTH_CANCELLING));
  894. TerminalThread->Cancel();
  895. }
  896. }
  897. FAuthenticationCancelled = true;
  898. }
  899. //---------------------------------------------------------------------------
  900. TAuthenticateForm * __fastcall TTerminalManager::MakeAuthenticateForm(
  901. TTerminal * Terminal)
  902. {
  903. TAuthenticateForm * Dialog = SafeFormCreate<TAuthenticateForm>();
  904. Dialog->Init(Terminal);
  905. DebugAssert(Dialog->OnCancel == NULL);
  906. Dialog->OnCancel = AuthenticateFormCancel;
  907. return Dialog;
  908. }
  909. //---------------------------------------------------------------------------
  910. void __fastcall TTerminalManager::FileNameInputDialogInitializeRenameBaseName(
  911. TObject * /*Sender*/, TInputDialogData * Data)
  912. {
  913. EditSelectBaseName(Data->Edit->Handle);
  914. }
  915. //---------------------------------------------------------------------------
  916. void __fastcall TTerminalManager::TerminalPromptUser(
  917. TTerminal * Terminal, TPromptKind Kind, UnicodeString Name, UnicodeString Instructions,
  918. TStrings * Prompts, TStrings * Results, bool & Result, void * /*Arg*/)
  919. {
  920. if (((Kind == pkPrompt) || (Kind == pkFileName)) && (FAuthenticateForm == NULL) &&
  921. (Terminal->Status != ssOpening))
  922. {
  923. DebugAssert(Instructions.IsEmpty());
  924. DebugAssert(Prompts->Count == 1);
  925. DebugAssert(FLAGSET(int(Prompts->Objects[0]), pupEcho));
  926. UnicodeString AResult = Results->Strings[0];
  927. TInputDialogInitialize InputDialogInitialize = NULL;
  928. if ((Kind == pkFileName) && !WinConfiguration->RenameWholeName)
  929. {
  930. InputDialogInitialize = FileNameInputDialogInitializeRenameBaseName;
  931. }
  932. Result = InputDialog(Name, Prompts->Strings[0], AResult, L"", NULL, false, InputDialogInitialize);
  933. if (Result)
  934. {
  935. Results->Strings[0] = AResult;
  936. }
  937. }
  938. else
  939. {
  940. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  941. if (AuthenticateForm == NULL)
  942. {
  943. AuthenticateForm = MakeAuthenticateForm(Terminal);
  944. }
  945. try
  946. {
  947. Result = AuthenticateForm->PromptUser(Kind, Name, Instructions, Prompts, Results,
  948. (FAuthenticateForm != NULL), Terminal->StoredCredentialsTried);
  949. }
  950. __finally
  951. {
  952. if (FAuthenticateForm == NULL)
  953. {
  954. delete AuthenticateForm;
  955. }
  956. }
  957. }
  958. }
  959. //---------------------------------------------------------------------------
  960. void __fastcall TTerminalManager::TerminalDisplayBanner(
  961. TTerminal * Terminal, UnicodeString SessionName,
  962. const UnicodeString & Banner, bool & NeverShowAgain, int Options)
  963. {
  964. DebugAssert(FAuthenticateForm != NULL);
  965. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  966. if (AuthenticateForm == NULL)
  967. {
  968. AuthenticateForm = MakeAuthenticateForm(Terminal);
  969. }
  970. try
  971. {
  972. AuthenticateForm->Banner(Banner, NeverShowAgain, Options);
  973. }
  974. __finally
  975. {
  976. if (FAuthenticateForm == NULL)
  977. {
  978. delete AuthenticateForm;
  979. }
  980. }
  981. }
  982. //---------------------------------------------------------------------------
  983. void __fastcall TTerminalManager::TerminalShowExtendedException(
  984. TTerminal * Terminal, Exception * E, void * /*Arg*/)
  985. {
  986. if (ScpExplorer)
  987. {
  988. ScpExplorer->ShowExtendedException(Terminal, E);
  989. }
  990. else
  991. {
  992. ShowExtendedExceptionEx(Terminal, E);
  993. }
  994. }
  995. //---------------------------------------------------------------------------
  996. static TDateTime DirectoryReadingProgressDelay(0, 0, 1, 500);
  997. //---------------------------------------------------------------------------
  998. void __fastcall TTerminalManager::TerminalReadDirectoryProgress(
  999. TObject * /*Sender*/, int Progress, int ResolvedLinks, bool & Cancel)
  1000. {
  1001. if (Progress == 0)
  1002. {
  1003. if (ScpExplorer != NULL)
  1004. {
  1005. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  1006. ScpExplorer->LockWindow();
  1007. }
  1008. FDirectoryReadingStart = Now();
  1009. if (!FProgressTitle.IsEmpty() || !FForegroundProgressTitle.IsEmpty())
  1010. {
  1011. FProgressTitle = L"";
  1012. FForegroundProgressTitle = L"";
  1013. UpdateAppTitle();
  1014. }
  1015. // Reset "was ESC ever pressed?" state
  1016. GetAsyncKeyState(VK_ESCAPE);
  1017. }
  1018. else if (Progress < 0)
  1019. {
  1020. if (Progress == -2)
  1021. {
  1022. // cancelled
  1023. if (ScpExplorer != NULL)
  1024. {
  1025. ScpExplorer->ReadDirectoryCancelled();
  1026. }
  1027. }
  1028. else
  1029. {
  1030. if (ScpExplorer != NULL)
  1031. {
  1032. ScpExplorer->UnlockWindow();
  1033. }
  1034. FProgressTitle = L"";
  1035. FForegroundProgressTitle = L"";
  1036. UpdateAppTitle();
  1037. }
  1038. }
  1039. else
  1040. {
  1041. // If the least significant bit is set,
  1042. // the key was pressed after the previous call to GetAsyncKeyState.
  1043. int KeyState = GetAsyncKeyState(VK_ESCAPE);
  1044. if (FLAGSET(KeyState, 0x01))
  1045. {
  1046. Cancel = true;
  1047. }
  1048. if ((Now() - FDirectoryReadingStart) >= DirectoryReadingProgressDelay)
  1049. {
  1050. // 4 is arbitrary number
  1051. FForegroundProgressTitle =
  1052. FMTLOAD(ResolvedLinks >= 4 ? DIRECTORY_READING_AND_RESOLVING_PROGRESS : DIRECTORY_READING_PROGRESS,
  1053. (Progress));
  1054. UpdateAppTitle();
  1055. }
  1056. }
  1057. }
  1058. //---------------------------------------------------------------------------
  1059. void __fastcall TTerminalManager::TerminalInformation(
  1060. TTerminal * Terminal, const UnicodeString & Str, bool /*Status*/, int Phase)
  1061. {
  1062. if (Phase == 1)
  1063. {
  1064. if (FAuthenticating == 0)
  1065. {
  1066. FBusyToken = BusyStart();
  1067. }
  1068. FAuthenticating++;
  1069. }
  1070. else if (Phase == 0)
  1071. {
  1072. DebugAssert(FAuthenticating > 0);
  1073. FAuthenticating--;
  1074. if (FAuthenticating == 0)
  1075. {
  1076. BusyEnd(FBusyToken);
  1077. FBusyToken = NULL;
  1078. }
  1079. SAFE_DESTROY(FAuthenticateForm);
  1080. }
  1081. else
  1082. {
  1083. if (FAuthenticating > 0)
  1084. {
  1085. bool ShowPending = false;
  1086. if (FAuthenticateForm == NULL)
  1087. {
  1088. FAuthenticateForm = MakeAuthenticateForm(Terminal);
  1089. ShowPending = true;
  1090. }
  1091. FAuthenticateForm->Log(Str);
  1092. if (ShowPending)
  1093. {
  1094. FAuthenticateForm->ShowAsModal();
  1095. }
  1096. }
  1097. }
  1098. }
  1099. //---------------------------------------------------------------------------
  1100. void __fastcall TTerminalManager::OperationFinished(::TFileOperation Operation,
  1101. TOperationSide Side, bool Temp, const UnicodeString & FileName, bool Success,
  1102. TOnceDoneOperation & OnceDoneOperation)
  1103. {
  1104. DebugAssert(ScpExplorer);
  1105. ScpExplorer->OperationFinished(Operation, Side, Temp, FileName, Success,
  1106. OnceDoneOperation);
  1107. }
  1108. //---------------------------------------------------------------------------
  1109. void __fastcall TTerminalManager::OperationProgress(
  1110. TFileOperationProgressType & ProgressData)
  1111. {
  1112. if (ProgressData.InProgress)
  1113. {
  1114. FProgressTitle = TProgressForm::ProgressStr(&ProgressData);
  1115. }
  1116. else
  1117. {
  1118. FProgressTitle = L"";
  1119. }
  1120. UpdateAppTitle();
  1121. DebugAssert(ScpExplorer);
  1122. ScpExplorer->OperationProgress(ProgressData);
  1123. }
  1124. //---------------------------------------------------------------------------
  1125. void __fastcall TTerminalManager::QueueEvent(TTerminalQueue * Queue, TQueueEvent Event)
  1126. {
  1127. TGuard Guard(FQueueSection);
  1128. FQueueEvents.push_back(std::make_pair(Queue, Event));
  1129. }
  1130. //---------------------------------------------------------------------------
  1131. void __fastcall TTerminalManager::ConfigurationChange(TObject * /*Sender*/)
  1132. {
  1133. DebugAssert(Configuration);
  1134. DebugAssert(Configuration == WinConfiguration);
  1135. if (!Application->Terminated && Configuration->Logging &&
  1136. (WinConfiguration->LogView == lvWindow))
  1137. {
  1138. if (ActiveTerminal)
  1139. {
  1140. RequireLogForm(LogMemo);
  1141. }
  1142. }
  1143. else
  1144. {
  1145. FreeLogForm();
  1146. }
  1147. TTerminalQueue * Queue;
  1148. for (int Index = 0; Index < Count; Index++)
  1149. {
  1150. DebugAssert(Terminals[Index]->Log);
  1151. Terminals[Index]->Log->ReflectSettings();
  1152. Terminals[Index]->ActionLog->ReflectSettings();
  1153. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1154. SetQueueConfiguration(Queue);
  1155. }
  1156. if (ScpExplorer)
  1157. {
  1158. ScpExplorer->ConfigurationChanged();
  1159. }
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. void __fastcall TTerminalManager::TerminalReady()
  1163. {
  1164. ScpExplorer->Terminal = ActiveTerminal;
  1165. ScpExplorer->Queue = ActiveQueue;
  1166. ScpExplorer->TerminalReady();
  1167. }
  1168. //---------------------------------------------------------------------------
  1169. TStrings * __fastcall TTerminalManager::GetTerminalList()
  1170. {
  1171. if (FTerminalList->Count != Count)
  1172. {
  1173. for (int i = 0; i < Count; i++)
  1174. {
  1175. UnicodeString NameN;
  1176. UnicodeString Name = Terminals[i]->SessionData->SessionName;
  1177. int Number = 1;
  1178. NameN = Name;
  1179. while (FTerminalList->IndexOf(NameN) >= 0)
  1180. {
  1181. Number++;
  1182. NameN = FORMAT(L"%s (%d)", (Name, Number));
  1183. }
  1184. if (Number > 1)
  1185. {
  1186. Name = FORMAT(L"%s (%d)", (Name, Number));
  1187. }
  1188. FTerminalList->AddObject(Name, Terminals[i]);
  1189. }
  1190. }
  1191. return FTerminalList;
  1192. }
  1193. //---------------------------------------------------------------------------
  1194. int __fastcall TTerminalManager::GetActiveTerminalIndex()
  1195. {
  1196. return ActiveTerminal ? IndexOf(ActiveTerminal) : -1;
  1197. }
  1198. //---------------------------------------------------------------------------
  1199. void __fastcall TTerminalManager::SetActiveTerminalIndex(int value)
  1200. {
  1201. ActiveTerminal = Terminals[value];
  1202. }
  1203. //---------------------------------------------------------------------------
  1204. UnicodeString __fastcall TTerminalManager::TerminalTitle(TTerminal * Terminal)
  1205. {
  1206. int Index = IndexOf(Terminal);
  1207. UnicodeString Result;
  1208. if (Index >= 0)
  1209. {
  1210. Result = TerminalList->Strings[Index];
  1211. }
  1212. else
  1213. {
  1214. // this is the case of background transfer sessions
  1215. Result = Terminal->SessionData->SessionName;
  1216. }
  1217. return Result;
  1218. }
  1219. //---------------------------------------------------------------------------
  1220. UnicodeString __fastcall TTerminalManager::GetActiveTerminalTitle()
  1221. {
  1222. UnicodeString Result = ActiveTerminal ?
  1223. TerminalTitle(ActiveTerminal) : UnicodeString(L"");
  1224. return Result;
  1225. }
  1226. //---------------------------------------------------------------------------
  1227. TTerminalQueue * __fastcall TTerminalManager::GetActiveQueue()
  1228. {
  1229. TTerminalQueue * Result = NULL;
  1230. if (ActiveTerminal != NULL)
  1231. {
  1232. Result = reinterpret_cast<TTerminalQueue *>(FQueues->Items[ActiveTerminalIndex]);
  1233. }
  1234. return Result;
  1235. }
  1236. //---------------------------------------------------------------------------
  1237. void __fastcall TTerminalManager::CycleTerminals(bool Forward)
  1238. {
  1239. int Index = ActiveTerminalIndex;
  1240. Index += Forward ? 1 : -1;
  1241. if (Index < 0)
  1242. {
  1243. Index = Count-1;
  1244. }
  1245. else if (Index >= Count)
  1246. {
  1247. Index = 0;
  1248. }
  1249. ActiveTerminalIndex = Index;
  1250. }
  1251. //---------------------------------------------------------------------------
  1252. bool __fastcall TTerminalManager::CanOpenInPutty()
  1253. {
  1254. return (ActiveTerminal != NULL) && !GUIConfiguration->PuttyPath.Trim().IsEmpty();
  1255. }
  1256. //---------------------------------------------------------------------------
  1257. void __fastcall TTerminalManager::UpdateSessionCredentials(TSessionData * Data)
  1258. {
  1259. Data->UserName = ActiveTerminal->UserName;
  1260. Data->Password = ActiveTerminal->Password;
  1261. }
  1262. //---------------------------------------------------------------------------
  1263. void __fastcall TTerminalManager::OpenInPutty()
  1264. {
  1265. Configuration->Usage->Inc(L"OpenInPutty");
  1266. TSessionData * Data = NULL;
  1267. try
  1268. {
  1269. // Is NULL on the first session when called from ConnectActiveTerminal()
  1270. // due to WinConfiguration->AutoOpenInPutty
  1271. if (ScpExplorer != NULL)
  1272. {
  1273. Data = ScpExplorer->CloneCurrentSessionData();
  1274. }
  1275. else
  1276. {
  1277. Data = new TSessionData(L"");
  1278. DebugAssert(ActiveTerminal != NULL);
  1279. Data->Assign(ActiveTerminal->SessionData);
  1280. UpdateSessionCredentials(Data);
  1281. }
  1282. // putty does not support resolving environment variables in session settings
  1283. Data->ExpandEnvironmentVariables();
  1284. if (ActiveTerminal->TunnelLocalPortNumber != 0)
  1285. {
  1286. Data->ConfigureTunnel(ActiveTerminal->TunnelLocalPortNumber);
  1287. }
  1288. OpenSessionInPutty(GUIConfiguration->PuttyPath, Data);
  1289. }
  1290. __finally
  1291. {
  1292. delete Data;
  1293. }
  1294. }
  1295. //---------------------------------------------------------------------------
  1296. void __fastcall TTerminalManager::NewSession(bool /*FromSite*/, const UnicodeString & SessionUrl, bool ReloadSessions)
  1297. {
  1298. if (ReloadSessions)
  1299. {
  1300. StoredSessions->Load();
  1301. }
  1302. UnicodeString DownloadFile; // unused
  1303. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1304. GetLoginData(SessionUrl, NULL, DataList.get(), DownloadFile, true);
  1305. if (DataList->Count > 0)
  1306. {
  1307. ActiveTerminal = NewTerminals(DataList.get());
  1308. }
  1309. }
  1310. //---------------------------------------------------------------------------
  1311. void __fastcall TTerminalManager::Idle()
  1312. {
  1313. for (int Index = 0; Index < Count; Index++)
  1314. {
  1315. TTerminal * Terminal = Terminals[Index];
  1316. try
  1317. {
  1318. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  1319. DebugAssert(ManagedTerminal != NULL);
  1320. // make sure Idle is called on the thread that runs the terminal
  1321. if (ManagedTerminal->TerminalThread != NULL)
  1322. {
  1323. ManagedTerminal->TerminalThread->Idle();
  1324. }
  1325. else
  1326. {
  1327. if (Terminal->Active)
  1328. {
  1329. Terminal->Idle();
  1330. }
  1331. }
  1332. if (Terminal->Active)
  1333. {
  1334. DebugAssert(Index < FQueues->Count);
  1335. if (Index < FQueues->Count)
  1336. {
  1337. reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index])->Idle();
  1338. }
  1339. }
  1340. }
  1341. catch(Exception & E)
  1342. {
  1343. if (Terminal == ActiveTerminal)
  1344. {
  1345. // throw further, so that the exception is handled in proper place
  1346. // (particularly in broken-transfer reconnect handler, bug 72)
  1347. throw;
  1348. }
  1349. else
  1350. {
  1351. // we may not have inactive terminal, unless there is a explorer,
  1352. // also Idle is called from explorer anyway
  1353. DebugAssert(ScpExplorer != NULL);
  1354. if (ScpExplorer != NULL)
  1355. {
  1356. ScpExplorer->InactiveTerminalException(Terminal, &E);
  1357. }
  1358. if (!Terminal->Active)
  1359. {
  1360. // if session is lost, save the error message and rethrow it
  1361. // once the terminal gets activated
  1362. FTerminationMessages->Strings[Index] = E.Message;
  1363. }
  1364. }
  1365. }
  1366. }
  1367. TTerminalQueue * QueueWithEvent;
  1368. TQueueEvent QueueEvent;
  1369. do
  1370. {
  1371. QueueWithEvent = NULL;
  1372. {
  1373. TGuard Guard(FQueueSection);
  1374. if (!FQueueEvents.empty())
  1375. {
  1376. QueueWithEvent = FQueueEvents[0].first;
  1377. QueueEvent = FQueueEvents[0].second;
  1378. FQueueEvents.erase(FQueueEvents.begin());
  1379. }
  1380. }
  1381. if (QueueWithEvent != NULL)
  1382. {
  1383. int Index = FQueues->IndexOf(QueueWithEvent);
  1384. // the session may not exist anymore
  1385. if (Index >= 0)
  1386. {
  1387. TTerminal * Terminal = Terminals[Index];
  1388. // we can hardly have a queue event without explorer
  1389. DebugAssert(ScpExplorer != NULL);
  1390. if (ScpExplorer != NULL)
  1391. {
  1392. ScpExplorer->QueueEvent(Terminal, QueueWithEvent, QueueEvent);
  1393. }
  1394. }
  1395. }
  1396. }
  1397. while (QueueWithEvent != NULL);
  1398. }
  1399. //---------------------------------------------------------------------------
  1400. void __fastcall TTerminalManager::MasterPasswordPrompt()
  1401. {
  1402. if (GetCurrentThreadId() == MainThreadID)
  1403. {
  1404. if (!DoMasterPasswordDialog())
  1405. {
  1406. Abort();
  1407. }
  1408. }
  1409. else
  1410. {
  1411. // this can happen only when we keep cancelling all master password prompts
  1412. // as long as the sessing finally connects (session password has to be
  1413. // explictly typed in), and background transfer is started
  1414. Abort();
  1415. }
  1416. }
  1417. //---------------------------------------------------------------------------
  1418. void __fastcall TTerminalManager::Move(TTerminal * Source, TTerminal * Target)
  1419. {
  1420. FTerminalList->Clear();
  1421. int SourceIndex = IndexOf(Source);
  1422. int TargetIndex = IndexOf(Target);
  1423. TTerminalList::Move(SourceIndex, TargetIndex);
  1424. FQueues->Move(SourceIndex, TargetIndex);
  1425. DoTerminalListChanged();
  1426. // when there are indexed sessions with the same name,
  1427. // the index may change when reordering the sessions
  1428. UpdateAppTitle();
  1429. }
  1430. //---------------------------------------------------------------------------
  1431. void __fastcall TTerminalManager::DoTerminalListChanged()
  1432. {
  1433. if (OnTerminalListChanged)
  1434. {
  1435. OnTerminalListChanged(this);
  1436. }
  1437. }
  1438. //---------------------------------------------------------------------------
  1439. void __fastcall TTerminalManager::SaveWorkspace(TList * DataList)
  1440. {
  1441. for (int Index = 0; Index < Count; Index++)
  1442. {
  1443. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminals[Index]);
  1444. TSessionData * Data = StoredSessions->SaveWorkspaceData(ManagedTerminal->StateData);
  1445. DataList->Add(Data);
  1446. Data->Name = IntToHex(Index, 4);
  1447. }
  1448. }
  1449. //---------------------------------------------------------------------------
  1450. TTerminal * __fastcall TTerminalManager::FindActiveTerminalForSite(TSessionData * Data)
  1451. {
  1452. TTerminal * Result = NULL;
  1453. for (int Index = 0; (Result == NULL) && (Index < Count); Index++)
  1454. {
  1455. TTerminal * Terminal = Terminals[Index];
  1456. if (Terminal->Active &&
  1457. Terminal->SessionData->IsSameSite(Data))
  1458. {
  1459. Result = Terminal;
  1460. }
  1461. }
  1462. return Result;
  1463. }
  1464. //---------------------------------------------------------------------------
  1465. TTerminalQueue * __fastcall TTerminalManager::FindQueueForTerminal(TTerminal * Terminal)
  1466. {
  1467. int Index = IndexOf(Terminal);
  1468. return reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1469. }