TerminalManager.cpp 46 KB

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