TerminalManager.cpp 47 KB

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