TerminalManager.cpp 46 KB

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