TerminalManager.cpp 45 KB

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