TerminalManager.cpp 46 KB

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