TerminalManager.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  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. try
  468. {
  469. if (ActiveTerminal && (Terminal == ActiveTerminal))
  470. {
  471. if ((Count > 0) && !FDestroying)
  472. {
  473. ActiveTerminal = Terminals[Index < Count ? Index : Index - 1];
  474. }
  475. else
  476. {
  477. ActiveTerminal = NULL;
  478. }
  479. }
  480. else
  481. {
  482. SaveTerminal(Terminal);
  483. }
  484. }
  485. // ActiveTerminal = NULL throws EAbort when Login dialog is closed
  486. __finally
  487. {
  488. // only now all references to/from queue (particularly events to explorer)
  489. // are cleared
  490. delete Queue;
  491. delete Terminal;
  492. DoTerminalListChanged();
  493. }
  494. }
  495. }
  496. //---------------------------------------------------------------------------
  497. void __fastcall TTerminalManager::SetScpExplorer(TCustomScpExplorerForm * value)
  498. {
  499. if (ScpExplorer != value)
  500. {
  501. // changing explorer is not supported yet
  502. DebugAssert(!ScpExplorer || !value);
  503. FScpExplorer = value;
  504. if (FScpExplorer)
  505. {
  506. FScpExplorer->Terminal = ActiveTerminal;
  507. FScpExplorer->Queue = ActiveQueue;
  508. FOnLastTerminalClosed = FScpExplorer->LastTerminalClosed;
  509. FOnTerminalListChanged = FScpExplorer->TerminalListChanged;
  510. UpdateTaskbarList();
  511. }
  512. else
  513. {
  514. FOnLastTerminalClosed = NULL;
  515. FOnTerminalListChanged = NULL;
  516. }
  517. }
  518. }
  519. //---------------------------------------------------------------------------
  520. void __fastcall TTerminalManager::SetActiveTerminal(TTerminal * value)
  521. {
  522. DoSetActiveTerminal(value, false);
  523. }
  524. //---------------------------------------------------------------------------
  525. void __fastcall TTerminalManager::SetActiveTerminalWithAutoReconnect(TTerminal * value)
  526. {
  527. DoSetActiveTerminal(value, true);
  528. }
  529. //---------------------------------------------------------------------------
  530. void __fastcall TTerminalManager::DoSetActiveTerminal(TTerminal * value, bool AutoReconnect)
  531. {
  532. if (ActiveTerminal != value)
  533. {
  534. // here used to be call to TCustomScpExporer::UpdateSessionData (now UpdateTerminal)
  535. // but it seems to be duplicate to call from TCustomScpExporer::TerminalChanging
  536. TTerminal * PActiveTerminal = ActiveTerminal;
  537. FActiveTerminal = value;
  538. // moved from else block of next if (ActiveTerminal) statement
  539. // so ScpExplorer can update its caption
  540. UpdateAppTitle();
  541. if (ScpExplorer)
  542. {
  543. if (ActiveTerminal && (ActiveTerminal->Status == ssOpened))
  544. {
  545. TerminalReady();
  546. }
  547. else
  548. {
  549. ScpExplorer->Terminal = NULL;
  550. ScpExplorer->Queue = NULL;
  551. }
  552. }
  553. if (PActiveTerminal && !PActiveTerminal->Active)
  554. {
  555. SaveTerminal(PActiveTerminal);
  556. }
  557. if (ActiveTerminal)
  558. {
  559. if (!PActiveTerminal)
  560. {
  561. CreateLogMemo();
  562. }
  563. DebugAssert(LogMemo);
  564. LogMemo->SessionLog = ActiveTerminal->Log;
  565. SwitchLogFormSessionLog();
  566. int Index = ActiveTerminalIndex;
  567. if (!ActiveTerminal->Active && !FTerminationMessages->Strings[Index].IsEmpty())
  568. {
  569. UnicodeString Message = FTerminationMessages->Strings[Index];
  570. FTerminationMessages->Strings[Index] = L"";
  571. if (AutoReconnect)
  572. {
  573. ReconnectActiveTerminal();
  574. }
  575. else
  576. {
  577. Exception * E = new ESshFatal(NULL, Message);
  578. try
  579. {
  580. // finally show pending terminal message,
  581. // this gives user also possibility to reconnect
  582. ActiveTerminal->ShowExtendedException(E);
  583. }
  584. __finally
  585. {
  586. delete E;
  587. }
  588. }
  589. }
  590. }
  591. else
  592. {
  593. if (LogForm)
  594. {
  595. FreeLogForm();
  596. }
  597. FreeLogMemo();
  598. if (OnLastTerminalClosed)
  599. {
  600. OnLastTerminalClosed(this);
  601. }
  602. }
  603. if ((ActiveTerminal != NULL) && !ActiveTerminal->Active)
  604. {
  605. ConnectActiveTerminal();
  606. }
  607. }
  608. }
  609. //---------------------------------------------------------------------------
  610. void __fastcall TTerminalManager::QueueStatusUpdated()
  611. {
  612. UpdateAppTitle();
  613. }
  614. //---------------------------------------------------------------------------
  615. void __fastcall TTerminalManager::UpdateAppTitle()
  616. {
  617. if (ScpExplorer)
  618. {
  619. UnicodeString NewTitle;
  620. if (ActiveTerminal)
  621. {
  622. NewTitle = FormatMainFormCaption(ActiveTerminalTitle);
  623. }
  624. else
  625. {
  626. NewTitle = FormatMainFormCaption(L"");
  627. }
  628. UnicodeString QueueProgressTitle;
  629. if (!FForegroundProgressTitle.IsEmpty())
  630. {
  631. NewTitle = FForegroundProgressTitle + L" - " + NewTitle;
  632. }
  633. else if (!FProgressTitle.IsEmpty() && !ForegroundTask())
  634. {
  635. NewTitle = FProgressTitle + L" - " + NewTitle;
  636. }
  637. else if ((ScpExplorer != NULL) && (ScpExplorer->Handle != GetAncestor(GetActiveWindow(), GA_ROOTOWNER)) &&
  638. !(QueueProgressTitle = ScpExplorer->GetQueueProgressTitle()).IsEmpty())
  639. {
  640. NewTitle = QueueProgressTitle + L" - " + NewTitle;
  641. }
  642. else if (ActiveTerminal && (ScpExplorer != NULL))
  643. {
  644. UnicodeString Path = ScpExplorer->PathForCaption();
  645. if (!Path.IsEmpty())
  646. {
  647. NewTitle = Path + L" - " + NewTitle;
  648. }
  649. }
  650. ScpExplorer->Caption = NewTitle;
  651. ScpExplorer->ApplicationTitleChanged();
  652. }
  653. }
  654. //---------------------------------------------------------------------------
  655. void __fastcall TTerminalManager::SaveTerminal(TTerminal * Terminal)
  656. {
  657. TSessionData * Data = StoredSessions->FindSame(Terminal->SessionData);
  658. if (Data != NULL)
  659. {
  660. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  661. DebugAssert(ManagedTerminal != NULL);
  662. bool Changed = false;
  663. if (Terminal->SessionData->UpdateDirectories)
  664. {
  665. Data->CopyDirectoriesStateData(ManagedTerminal->StateData);
  666. Changed = true;
  667. }
  668. if (Changed)
  669. {
  670. // modified only, implicit
  671. StoredSessions->Save(false, false);
  672. }
  673. }
  674. }
  675. //---------------------------------------------------------------------------
  676. void __fastcall TTerminalManager::CreateLogMemo()
  677. {
  678. DebugAssert(!FLogMemo);
  679. DebugAssert(ActiveTerminal);
  680. FLogMemo = new TLogMemo(Application);
  681. try
  682. {
  683. FLogMemo->SessionLog = ActiveTerminal->Log;
  684. FLogMemo->PopupMenu = NonVisualDataModule->LogMemoPopup;
  685. }
  686. catch (...)
  687. {
  688. delete FLogMemo;
  689. throw;
  690. }
  691. }
  692. //---------------------------------------------------------------------------
  693. void __fastcall TTerminalManager::FreeLogMemo()
  694. {
  695. DebugAssert(LogMemo);
  696. LogMemo->PopupMenu = NULL;
  697. SAFE_DESTROY(FLogMemo);
  698. }
  699. //---------------------------------------------------------------------------
  700. void __fastcall TTerminalManager::HandleException(Exception * E)
  701. {
  702. // can be null for example when exception is thrown on login dialog
  703. if (ActiveTerminal != NULL)
  704. {
  705. ActiveTerminal->ShowExtendedException(E);
  706. }
  707. else
  708. {
  709. ShowExtendedException(E);
  710. }
  711. }
  712. //---------------------------------------------------------------------------
  713. void __fastcall TTerminalManager::ApplicationException(TObject * /*Sender*/,
  714. Exception * E)
  715. {
  716. HandleException(E);
  717. }
  718. //---------------------------------------------------------------------------
  719. void __fastcall TTerminalManager::ApplicationShowHint(UnicodeString & HintStr,
  720. bool & /*CanShow*/, THintInfo & HintInfo)
  721. {
  722. TLabel * HintLabel = dynamic_cast<TLabel *>(HintInfo.HintControl);
  723. if ((HintLabel != NULL) && (HintLabel->Caption == HintStr))
  724. {
  725. // Hack for transfer setting labels.
  726. // Should be converted to something like HintLabel()
  727. HintInfo.HintPos = HintLabel->ClientToScreen(TPoint(0, 0));
  728. HintInfo.HintMaxWidth = HintLabel->Width;
  729. HintInfo.HideTimeout = 100000; // "almost" never
  730. }
  731. else if (dynamic_cast<TProgressBar *>(HintInfo.HintControl) != NULL)
  732. {
  733. // Hint is forcibly hidden in TProgressForm::FormHide
  734. HintInfo.HideTimeout = 100000; // "almost" never
  735. HintInfo.ReshowTimeout = 500; // updated each 0.5s
  736. }
  737. else
  738. {
  739. int HintMaxWidth = 300;
  740. TControl * ScaleControl = HintInfo.HintControl;
  741. if (DebugAlwaysFalse(HintInfo.HintControl == NULL) ||
  742. (GetParentForm(HintInfo.HintControl) == NULL))
  743. {
  744. ScaleControl = ScpExplorer;
  745. }
  746. HintMaxWidth = ScaleByTextHeight(ScaleControl, HintMaxWidth);
  747. HintInfo.HintMaxWidth = HintMaxWidth;
  748. }
  749. }
  750. //---------------------------------------------------------------------------
  751. bool __fastcall TTerminalManager::HandleMouseWheel(WPARAM WParam, LPARAM LParam)
  752. {
  753. bool Result = false;
  754. if (Application->Active)
  755. {
  756. TPoint Point(LOWORD(LParam), HIWORD(LParam));
  757. TWinControl * Control = FindVCLWindow(Point);
  758. if (Control != NULL)
  759. {
  760. TCustomForm * Form = GetParentForm(Control);
  761. // Only case we expect the parent form to be NULL is on the Find/Replace dialog,
  762. // which is owned by VCL's internal TRedirectorWindow.
  763. DebugAssert((Form != NULL) || (Control->ClassName() == L"TRedirectorWindow"));
  764. if ((Form != NULL) && Form->Active)
  765. {
  766. // Send it only to windows we tested it with.
  767. // Though we should sooner or later remove this test and pass it to all our windows.
  768. if (Form->Perform(WM_WANTS_MOUSEWHEEL, 0, 0) == 1)
  769. {
  770. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  771. Result = true;
  772. }
  773. }
  774. }
  775. }
  776. return Result;
  777. }
  778. //---------------------------------------------------------------------------
  779. void __fastcall TTerminalManager::ApplicationMessage(TMsg & Msg, bool & Handled)
  780. {
  781. if (Msg.message == FTaskbarButtonCreatedMessage)
  782. {
  783. CreateTaskbarList();
  784. }
  785. if (Msg.message == WM_MOUSEWHEEL)
  786. {
  787. Handled = HandleMouseWheel(Msg.wParam, Msg.lParam);
  788. }
  789. }
  790. //---------------------------------------------------------------------------
  791. void __fastcall TTerminalManager::ApplicationModalBegin(TObject * /*Sender*/)
  792. {
  793. NonVisualDataModule->StartBusy();
  794. if (ScpExplorer != NULL)
  795. {
  796. ScpExplorer->SuspendWindowLock();
  797. }
  798. }
  799. //---------------------------------------------------------------------------
  800. void __fastcall TTerminalManager::ApplicationModalEnd(TObject * /*Sender*/)
  801. {
  802. NonVisualDataModule->EndBusy();
  803. if (ScpExplorer != NULL)
  804. {
  805. ScpExplorer->ResumeWindowLock();
  806. }
  807. }
  808. //---------------------------------------------------------------------------
  809. void __fastcall TTerminalManager::InitTaskbarButtonCreatedMessage()
  810. {
  811. // XE6 VCL already handles TaskbarButtonCreated, but does not call ChangeWindowMessageFilterEx.
  812. // So we keep our implementation.
  813. // See also http://stackoverflow.com/a/14618587/850848
  814. FTaskbarButtonCreatedMessage = RegisterWindowMessage(L"TaskbarButtonCreated");
  815. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  816. ChangeWindowMessageFilterExProc ChangeWindowMessageFilterEx =
  817. (ChangeWindowMessageFilterExProc)GetProcAddress(User32Library, "ChangeWindowMessageFilterEx");
  818. if (ChangeWindowMessageFilterEx != NULL)
  819. {
  820. // without this we won't get TaskbarButtonCreated, when app is running elevated
  821. ChangeWindowMessageFilterEx(
  822. Application->Handle, FTaskbarButtonCreatedMessage, MSGFLT_ALLOW, NULL);
  823. }
  824. }
  825. //---------------------------------------------------------------------------
  826. void __fastcall TTerminalManager::CreateTaskbarList()
  827. {
  828. ReleaseTaskbarList();
  829. if(SUCCEEDED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL,
  830. IID_ITaskbarList3, (void **) &FTaskbarList)))
  831. {
  832. if (ScpExplorer != NULL)
  833. {
  834. UpdateTaskbarList();
  835. }
  836. }
  837. }
  838. //---------------------------------------------------------------------------
  839. void __fastcall TTerminalManager::ReleaseTaskbarList()
  840. {
  841. if (FTaskbarList != NULL)
  842. {
  843. FTaskbarList->Release();
  844. }
  845. }
  846. //---------------------------------------------------------------------------
  847. void __fastcall TTerminalManager::UpdateTaskbarList()
  848. {
  849. ScpExplorer->UpdateTaskbarList(FTaskbarList);
  850. }
  851. //---------------------------------------------------------------------------
  852. void __fastcall TTerminalManager::DeleteLocalFile(const UnicodeString FileName, bool Alternative)
  853. {
  854. RecursiveDeleteFileChecked(FileName, (WinConfiguration->DeleteToRecycleBin != Alternative));
  855. }
  856. //---------------------------------------------------------------------------
  857. void __fastcall TTerminalManager::TerminalQueryUser(TObject * Sender,
  858. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  859. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * /*Arg*/)
  860. {
  861. UnicodeString HelpKeyword;
  862. TMessageParams MessageParams(Params);
  863. UnicodeString AQuery = Query;
  864. if (Params != NULL)
  865. {
  866. HelpKeyword = Params->HelpKeyword;
  867. if (FLAGSET(Params->Params, qpFatalAbort))
  868. {
  869. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  870. if (!MessageParams.TimerMessage.IsEmpty())
  871. {
  872. MessageParams.TimerMessage = FMTLOAD(WARN_FATAL_ERROR, (MessageParams.TimerMessage));
  873. }
  874. }
  875. }
  876. if (ScpExplorer)
  877. {
  878. Answer = ScpExplorer->MoreMessageDialog(AQuery, MoreMessages, Type, Answers,
  879. HelpKeyword, &MessageParams, dynamic_cast<TTerminal *>(Sender));
  880. }
  881. else
  882. {
  883. Answer = MoreMessageDialog(AQuery, MoreMessages, Type, Answers, HelpKeyword,
  884. &MessageParams);
  885. }
  886. }
  887. //---------------------------------------------------------------------------
  888. void __fastcall TTerminalManager::AuthenticateFormCancel(TObject * Sender)
  889. {
  890. TAuthenticateForm * Form = dynamic_cast<TAuthenticateForm *>(Sender);
  891. DebugAssert(Form != NULL);
  892. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Form->Terminal);
  893. // will be null e.g. for background transfers
  894. if (ManagedTerminal != NULL)
  895. {
  896. TTerminalThread * TerminalThread = ManagedTerminal->TerminalThread;
  897. // can be NULL for reconnects from transfers
  898. if ((TerminalThread != NULL) && !TerminalThread->Cancelling)
  899. {
  900. Form->Log(LoadStr(AUTH_CANCELLING));
  901. TerminalThread->Cancel();
  902. }
  903. }
  904. FAuthenticationCancelled = true;
  905. }
  906. //---------------------------------------------------------------------------
  907. TAuthenticateForm * __fastcall TTerminalManager::MakeAuthenticateForm(
  908. TTerminal * Terminal)
  909. {
  910. TAuthenticateForm * Dialog = SafeFormCreate<TAuthenticateForm>();
  911. Dialog->Init(Terminal);
  912. DebugAssert(Dialog->OnCancel == NULL);
  913. Dialog->OnCancel = AuthenticateFormCancel;
  914. return Dialog;
  915. }
  916. //---------------------------------------------------------------------------
  917. void __fastcall TTerminalManager::FileNameInputDialogInitializeRenameBaseName(
  918. TObject * /*Sender*/, TInputDialogData * Data)
  919. {
  920. EditSelectBaseName(Data->Edit->Handle);
  921. }
  922. //---------------------------------------------------------------------------
  923. void __fastcall TTerminalManager::TerminalPromptUser(
  924. TTerminal * Terminal, TPromptKind Kind, UnicodeString Name, UnicodeString Instructions,
  925. TStrings * Prompts, TStrings * Results, bool & Result, void * /*Arg*/)
  926. {
  927. if (((Kind == pkPrompt) || (Kind == pkFileName)) && (FAuthenticateForm == NULL) &&
  928. (Terminal->Status != ssOpening))
  929. {
  930. DebugAssert(Instructions.IsEmpty());
  931. DebugAssert(Prompts->Count == 1);
  932. DebugAssert(FLAGSET(int(Prompts->Objects[0]), pupEcho));
  933. UnicodeString AResult = Results->Strings[0];
  934. TInputDialogInitialize InputDialogInitialize = NULL;
  935. if ((Kind == pkFileName) && !WinConfiguration->RenameWholeName)
  936. {
  937. InputDialogInitialize = FileNameInputDialogInitializeRenameBaseName;
  938. }
  939. Result = InputDialog(Name, Prompts->Strings[0], AResult, L"", NULL, false, InputDialogInitialize);
  940. if (Result)
  941. {
  942. Results->Strings[0] = AResult;
  943. }
  944. }
  945. else
  946. {
  947. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  948. if (AuthenticateForm == NULL)
  949. {
  950. AuthenticateForm = MakeAuthenticateForm(Terminal);
  951. }
  952. try
  953. {
  954. Result = AuthenticateForm->PromptUser(Kind, Name, Instructions, Prompts, Results,
  955. (FAuthenticateForm != NULL), Terminal->StoredCredentialsTried);
  956. }
  957. __finally
  958. {
  959. if (FAuthenticateForm == NULL)
  960. {
  961. delete AuthenticateForm;
  962. }
  963. }
  964. }
  965. }
  966. //---------------------------------------------------------------------------
  967. void __fastcall TTerminalManager::TerminalDisplayBanner(
  968. TTerminal * Terminal, UnicodeString SessionName,
  969. const UnicodeString & Banner, bool & NeverShowAgain, int Options)
  970. {
  971. DebugAssert(FAuthenticateForm != NULL);
  972. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  973. if (AuthenticateForm == NULL)
  974. {
  975. AuthenticateForm = MakeAuthenticateForm(Terminal);
  976. }
  977. try
  978. {
  979. AuthenticateForm->Banner(Banner, NeverShowAgain, Options);
  980. }
  981. __finally
  982. {
  983. if (FAuthenticateForm == NULL)
  984. {
  985. delete AuthenticateForm;
  986. }
  987. }
  988. }
  989. //---------------------------------------------------------------------------
  990. void __fastcall TTerminalManager::TerminalShowExtendedException(
  991. TTerminal * Terminal, Exception * E, void * /*Arg*/)
  992. {
  993. if (ScpExplorer)
  994. {
  995. ScpExplorer->ShowExtendedException(Terminal, E);
  996. }
  997. else
  998. {
  999. ShowExtendedExceptionEx(Terminal, E);
  1000. }
  1001. }
  1002. //---------------------------------------------------------------------------
  1003. static TDateTime DirectoryReadingProgressDelay(0, 0, 1, 500);
  1004. //---------------------------------------------------------------------------
  1005. void __fastcall TTerminalManager::TerminalReadDirectoryProgress(
  1006. TObject * /*Sender*/, int Progress, int ResolvedLinks, bool & Cancel)
  1007. {
  1008. if (Progress == 0)
  1009. {
  1010. if (ScpExplorer != NULL)
  1011. {
  1012. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  1013. ScpExplorer->LockWindow();
  1014. }
  1015. FDirectoryReadingStart = Now();
  1016. if (!FProgressTitle.IsEmpty() || !FForegroundProgressTitle.IsEmpty())
  1017. {
  1018. FProgressTitle = L"";
  1019. FForegroundProgressTitle = L"";
  1020. UpdateAppTitle();
  1021. }
  1022. // Reset "was ESC ever pressed?" state
  1023. GetAsyncKeyState(VK_ESCAPE);
  1024. }
  1025. else if (Progress < 0)
  1026. {
  1027. if (Progress == -2)
  1028. {
  1029. // cancelled
  1030. if (ScpExplorer != NULL)
  1031. {
  1032. ScpExplorer->ReadDirectoryCancelled();
  1033. }
  1034. }
  1035. else
  1036. {
  1037. if (ScpExplorer != NULL)
  1038. {
  1039. ScpExplorer->UnlockWindow();
  1040. }
  1041. FProgressTitle = L"";
  1042. FForegroundProgressTitle = L"";
  1043. UpdateAppTitle();
  1044. }
  1045. }
  1046. else
  1047. {
  1048. // If the least significant bit is set,
  1049. // the key was pressed after the previous call to GetAsyncKeyState.
  1050. int KeyState = GetAsyncKeyState(VK_ESCAPE);
  1051. if (FLAGSET(KeyState, 0x01))
  1052. {
  1053. Cancel = true;
  1054. }
  1055. if ((Now() - FDirectoryReadingStart) >= DirectoryReadingProgressDelay)
  1056. {
  1057. // 4 is arbitrary number
  1058. FForegroundProgressTitle =
  1059. FMTLOAD(ResolvedLinks >= 4 ? DIRECTORY_READING_AND_RESOLVING_PROGRESS : DIRECTORY_READING_PROGRESS,
  1060. (Progress));
  1061. UpdateAppTitle();
  1062. }
  1063. }
  1064. }
  1065. //---------------------------------------------------------------------------
  1066. void __fastcall TTerminalManager::TerminalInformation(
  1067. TTerminal * Terminal, const UnicodeString & Str, bool /*Status*/, int Phase)
  1068. {
  1069. if (Phase == 1)
  1070. {
  1071. if (FAuthenticating == 0)
  1072. {
  1073. FBusyToken = BusyStart();
  1074. }
  1075. FAuthenticating++;
  1076. }
  1077. else if (Phase == 0)
  1078. {
  1079. DebugAssert(FAuthenticating > 0);
  1080. FAuthenticating--;
  1081. if (FAuthenticating == 0)
  1082. {
  1083. BusyEnd(FBusyToken);
  1084. FBusyToken = NULL;
  1085. }
  1086. SAFE_DESTROY(FAuthenticateForm);
  1087. }
  1088. else
  1089. {
  1090. if (FAuthenticating > 0)
  1091. {
  1092. bool ShowPending = false;
  1093. if (FAuthenticateForm == NULL)
  1094. {
  1095. FAuthenticateForm = MakeAuthenticateForm(Terminal);
  1096. ShowPending = true;
  1097. }
  1098. FAuthenticateForm->Log(Str);
  1099. if (ShowPending)
  1100. {
  1101. FAuthenticateForm->ShowAsModal();
  1102. }
  1103. }
  1104. }
  1105. }
  1106. //---------------------------------------------------------------------------
  1107. void __fastcall TTerminalManager::OperationFinished(::TFileOperation Operation,
  1108. TOperationSide Side, bool Temp, const UnicodeString & FileName, bool Success,
  1109. TOnceDoneOperation & OnceDoneOperation)
  1110. {
  1111. DebugAssert(ScpExplorer);
  1112. ScpExplorer->OperationFinished(Operation, Side, Temp, FileName, Success,
  1113. OnceDoneOperation);
  1114. }
  1115. //---------------------------------------------------------------------------
  1116. void __fastcall TTerminalManager::OperationProgress(
  1117. TFileOperationProgressType & ProgressData)
  1118. {
  1119. if (ProgressData.InProgress)
  1120. {
  1121. FProgressTitle = TProgressForm::ProgressStr(&ProgressData);
  1122. }
  1123. else
  1124. {
  1125. FProgressTitle = L"";
  1126. }
  1127. UpdateAppTitle();
  1128. DebugAssert(ScpExplorer);
  1129. ScpExplorer->OperationProgress(ProgressData);
  1130. }
  1131. //---------------------------------------------------------------------------
  1132. void __fastcall TTerminalManager::QueueEvent(TTerminalQueue * Queue, TQueueEvent Event)
  1133. {
  1134. TGuard Guard(FQueueSection);
  1135. FQueueEvents.push_back(std::make_pair(Queue, Event));
  1136. }
  1137. //---------------------------------------------------------------------------
  1138. void __fastcall TTerminalManager::ConfigurationChange(TObject * /*Sender*/)
  1139. {
  1140. DebugAssert(Configuration);
  1141. DebugAssert(Configuration == WinConfiguration);
  1142. if (!Application->Terminated && Configuration->Logging &&
  1143. (WinConfiguration->LogView == lvWindow))
  1144. {
  1145. if (ActiveTerminal)
  1146. {
  1147. RequireLogForm(LogMemo);
  1148. }
  1149. }
  1150. else
  1151. {
  1152. FreeLogForm();
  1153. }
  1154. TTerminalQueue * Queue;
  1155. for (int Index = 0; Index < Count; Index++)
  1156. {
  1157. DebugAssert(Terminals[Index]->Log);
  1158. Terminals[Index]->Log->ReflectSettings();
  1159. Terminals[Index]->ActionLog->ReflectSettings();
  1160. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1161. SetQueueConfiguration(Queue);
  1162. }
  1163. if (ScpExplorer)
  1164. {
  1165. ScpExplorer->ConfigurationChanged();
  1166. }
  1167. }
  1168. //---------------------------------------------------------------------------
  1169. void __fastcall TTerminalManager::TerminalReady()
  1170. {
  1171. ScpExplorer->Terminal = ActiveTerminal;
  1172. ScpExplorer->Queue = ActiveQueue;
  1173. ScpExplorer->TerminalReady();
  1174. }
  1175. //---------------------------------------------------------------------------
  1176. TStrings * __fastcall TTerminalManager::GetTerminalList()
  1177. {
  1178. if (FTerminalList->Count != Count)
  1179. {
  1180. for (int i = 0; i < Count; i++)
  1181. {
  1182. UnicodeString NameN;
  1183. UnicodeString Name = Terminals[i]->SessionData->SessionName;
  1184. int Number = 1;
  1185. NameN = Name;
  1186. while (FTerminalList->IndexOf(NameN) >= 0)
  1187. {
  1188. Number++;
  1189. NameN = FORMAT(L"%s (%d)", (Name, Number));
  1190. }
  1191. if (Number > 1)
  1192. {
  1193. Name = FORMAT(L"%s (%d)", (Name, Number));
  1194. }
  1195. FTerminalList->AddObject(Name, Terminals[i]);
  1196. }
  1197. }
  1198. return FTerminalList;
  1199. }
  1200. //---------------------------------------------------------------------------
  1201. int __fastcall TTerminalManager::GetActiveTerminalIndex()
  1202. {
  1203. return ActiveTerminal ? IndexOf(ActiveTerminal) : -1;
  1204. }
  1205. //---------------------------------------------------------------------------
  1206. void __fastcall TTerminalManager::SetActiveTerminalIndex(int value)
  1207. {
  1208. ActiveTerminal = Terminals[value];
  1209. }
  1210. //---------------------------------------------------------------------------
  1211. UnicodeString __fastcall TTerminalManager::TerminalTitle(TTerminal * Terminal)
  1212. {
  1213. int Index = IndexOf(Terminal);
  1214. UnicodeString Result;
  1215. if (Index >= 0)
  1216. {
  1217. Result = TerminalList->Strings[Index];
  1218. }
  1219. else
  1220. {
  1221. // this is the case of background transfer sessions
  1222. Result = Terminal->SessionData->SessionName;
  1223. }
  1224. return Result;
  1225. }
  1226. //---------------------------------------------------------------------------
  1227. UnicodeString __fastcall TTerminalManager::GetActiveTerminalTitle()
  1228. {
  1229. UnicodeString Result = ActiveTerminal ?
  1230. TerminalTitle(ActiveTerminal) : UnicodeString(L"");
  1231. return Result;
  1232. }
  1233. //---------------------------------------------------------------------------
  1234. TTerminalQueue * __fastcall TTerminalManager::GetActiveQueue()
  1235. {
  1236. TTerminalQueue * Result = NULL;
  1237. if (ActiveTerminal != NULL)
  1238. {
  1239. Result = reinterpret_cast<TTerminalQueue *>(FQueues->Items[ActiveTerminalIndex]);
  1240. }
  1241. return Result;
  1242. }
  1243. //---------------------------------------------------------------------------
  1244. void __fastcall TTerminalManager::CycleTerminals(bool Forward)
  1245. {
  1246. int Index = ActiveTerminalIndex;
  1247. Index += Forward ? 1 : -1;
  1248. if (Index < 0)
  1249. {
  1250. Index = Count-1;
  1251. }
  1252. else if (Index >= Count)
  1253. {
  1254. Index = 0;
  1255. }
  1256. ActiveTerminalIndex = Index;
  1257. }
  1258. //---------------------------------------------------------------------------
  1259. bool __fastcall TTerminalManager::CanOpenInPutty()
  1260. {
  1261. return (ActiveTerminal != NULL) && !GUIConfiguration->PuttyPath.Trim().IsEmpty();
  1262. }
  1263. //---------------------------------------------------------------------------
  1264. void __fastcall TTerminalManager::UpdateSessionCredentials(TSessionData * Data)
  1265. {
  1266. Data->UserName = ActiveTerminal->UserName;
  1267. Data->Password = ActiveTerminal->Password;
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. void __fastcall TTerminalManager::OpenInPutty()
  1271. {
  1272. Configuration->Usage->Inc(L"OpenInPutty");
  1273. TSessionData * Data = NULL;
  1274. try
  1275. {
  1276. // Is NULL on the first session when called from ConnectActiveTerminal()
  1277. // due to WinConfiguration->AutoOpenInPutty
  1278. if (ScpExplorer != NULL)
  1279. {
  1280. Data = ScpExplorer->CloneCurrentSessionData();
  1281. }
  1282. else
  1283. {
  1284. Data = new TSessionData(L"");
  1285. DebugAssert(ActiveTerminal != NULL);
  1286. Data->Assign(ActiveTerminal->SessionData);
  1287. UpdateSessionCredentials(Data);
  1288. }
  1289. // putty does not support resolving environment variables in session settings
  1290. Data->ExpandEnvironmentVariables();
  1291. if (ActiveTerminal->TunnelLocalPortNumber != 0)
  1292. {
  1293. Data->ConfigureTunnel(ActiveTerminal->TunnelLocalPortNumber);
  1294. }
  1295. OpenSessionInPutty(GUIConfiguration->PuttyPath, Data);
  1296. }
  1297. __finally
  1298. {
  1299. delete Data;
  1300. }
  1301. }
  1302. //---------------------------------------------------------------------------
  1303. void __fastcall TTerminalManager::NewSession(bool /*FromSite*/, const UnicodeString & SessionUrl, bool ReloadSessions)
  1304. {
  1305. if (ReloadSessions)
  1306. {
  1307. StoredSessions->Load();
  1308. }
  1309. UnicodeString DownloadFile; // unused
  1310. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1311. GetLoginData(SessionUrl, NULL, DataList.get(), DownloadFile, true);
  1312. if (DataList->Count > 0)
  1313. {
  1314. ActiveTerminal = NewTerminals(DataList.get());
  1315. }
  1316. }
  1317. //---------------------------------------------------------------------------
  1318. void __fastcall TTerminalManager::Idle()
  1319. {
  1320. for (int Index = 0; Index < Count; Index++)
  1321. {
  1322. TTerminal * Terminal = Terminals[Index];
  1323. try
  1324. {
  1325. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  1326. DebugAssert(ManagedTerminal != NULL);
  1327. // make sure Idle is called on the thread that runs the terminal
  1328. if (ManagedTerminal->TerminalThread != NULL)
  1329. {
  1330. ManagedTerminal->TerminalThread->Idle();
  1331. }
  1332. else
  1333. {
  1334. if (Terminal->Active)
  1335. {
  1336. Terminal->Idle();
  1337. }
  1338. }
  1339. if (Terminal->Active)
  1340. {
  1341. DebugAssert(Index < FQueues->Count);
  1342. if (Index < FQueues->Count)
  1343. {
  1344. reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index])->Idle();
  1345. }
  1346. }
  1347. }
  1348. catch(Exception & E)
  1349. {
  1350. if (Terminal == ActiveTerminal)
  1351. {
  1352. // throw further, so that the exception is handled in proper place
  1353. // (particularly in broken-transfer reconnect handler, bug 72)
  1354. throw;
  1355. }
  1356. else
  1357. {
  1358. // we may not have inactive terminal, unless there is a explorer,
  1359. // also Idle is called from explorer anyway
  1360. DebugAssert(ScpExplorer != NULL);
  1361. if (ScpExplorer != NULL)
  1362. {
  1363. ScpExplorer->InactiveTerminalException(Terminal, &E);
  1364. }
  1365. if (!Terminal->Active)
  1366. {
  1367. // if session is lost, save the error message and rethrow it
  1368. // once the terminal gets activated
  1369. FTerminationMessages->Strings[Index] = E.Message;
  1370. }
  1371. }
  1372. }
  1373. }
  1374. TTerminalQueue * QueueWithEvent;
  1375. TQueueEvent QueueEvent;
  1376. do
  1377. {
  1378. QueueWithEvent = NULL;
  1379. {
  1380. TGuard Guard(FQueueSection);
  1381. if (!FQueueEvents.empty())
  1382. {
  1383. QueueWithEvent = FQueueEvents[0].first;
  1384. QueueEvent = FQueueEvents[0].second;
  1385. FQueueEvents.erase(FQueueEvents.begin());
  1386. }
  1387. }
  1388. if (QueueWithEvent != NULL)
  1389. {
  1390. int Index = FQueues->IndexOf(QueueWithEvent);
  1391. // the session may not exist anymore
  1392. if (Index >= 0)
  1393. {
  1394. TTerminal * Terminal = Terminals[Index];
  1395. // we can hardly have a queue event without explorer
  1396. DebugAssert(ScpExplorer != NULL);
  1397. if (ScpExplorer != NULL)
  1398. {
  1399. ScpExplorer->QueueEvent(Terminal, QueueWithEvent, QueueEvent);
  1400. }
  1401. }
  1402. }
  1403. }
  1404. while (QueueWithEvent != NULL);
  1405. }
  1406. //---------------------------------------------------------------------------
  1407. void __fastcall TTerminalManager::MasterPasswordPrompt()
  1408. {
  1409. if (GetCurrentThreadId() == MainThreadID)
  1410. {
  1411. if (!DoMasterPasswordDialog())
  1412. {
  1413. Abort();
  1414. }
  1415. }
  1416. else
  1417. {
  1418. // this can happen only when we keep cancelling all master password prompts
  1419. // as long as the sessing finally connects (session password has to be
  1420. // explictly typed in), and background transfer is started
  1421. Abort();
  1422. }
  1423. }
  1424. //---------------------------------------------------------------------------
  1425. void __fastcall TTerminalManager::Move(TTerminal * Source, TTerminal * Target)
  1426. {
  1427. FTerminalList->Clear();
  1428. int SourceIndex = IndexOf(Source);
  1429. int TargetIndex = IndexOf(Target);
  1430. TTerminalList::Move(SourceIndex, TargetIndex);
  1431. FQueues->Move(SourceIndex, TargetIndex);
  1432. DoTerminalListChanged();
  1433. // when there are indexed sessions with the same name,
  1434. // the index may change when reordering the sessions
  1435. UpdateAppTitle();
  1436. }
  1437. //---------------------------------------------------------------------------
  1438. void __fastcall TTerminalManager::DoTerminalListChanged()
  1439. {
  1440. if (OnTerminalListChanged)
  1441. {
  1442. OnTerminalListChanged(this);
  1443. }
  1444. }
  1445. //---------------------------------------------------------------------------
  1446. void __fastcall TTerminalManager::SaveWorkspace(TList * DataList)
  1447. {
  1448. for (int Index = 0; Index < Count; Index++)
  1449. {
  1450. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminals[Index]);
  1451. TSessionData * Data = StoredSessions->SaveWorkspaceData(ManagedTerminal->StateData);
  1452. DataList->Add(Data);
  1453. Data->Name = IntToHex(Index, 4);
  1454. }
  1455. }
  1456. //---------------------------------------------------------------------------
  1457. TTerminal * __fastcall TTerminalManager::FindActiveTerminalForSite(TSessionData * Data)
  1458. {
  1459. TTerminal * Result = NULL;
  1460. for (int Index = 0; (Result == NULL) && (Index < Count); Index++)
  1461. {
  1462. TTerminal * Terminal = Terminals[Index];
  1463. if (Terminal->Active &&
  1464. Terminal->SessionData->IsSameSite(Data))
  1465. {
  1466. Result = Terminal;
  1467. }
  1468. }
  1469. return Result;
  1470. }
  1471. //---------------------------------------------------------------------------
  1472. TTerminalQueue * __fastcall TTerminalManager::FindQueueForTerminal(TTerminal * Terminal)
  1473. {
  1474. int Index = IndexOf(Terminal);
  1475. return reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1476. }