TerminalManager.cpp 45 KB

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