TerminalManager.cpp 46 KB

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