TerminalManager.cpp 46 KB

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