TerminalManager.cpp 46 KB

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