TerminalManager.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027
  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 "NonVisual.h"
  9. #include "WinConfiguration.h"
  10. #include "Tools.h"
  11. #include <Common.h>
  12. #include <CoreMain.h>
  13. #include <GUITools.h>
  14. #include <TextsWin.h>
  15. #include <TextsCore.h>
  16. #include <Progress.h>
  17. #include <Exceptions.h>
  18. #include <VCLCommon.h>
  19. #include <WinApi.h>
  20. #include <PuttyTools.h>
  21. #include <HelpWin.h>
  22. #include <System.IOUtils.hpp>
  23. #include <StrUtils.hpp>
  24. //---------------------------------------------------------------------------
  25. #pragma package(smart_init)
  26. //---------------------------------------------------------------------------
  27. TTerminalManager * TTerminalManager::FInstance = NULL;
  28. //---------------------------------------------------------------------------
  29. __fastcall TManagedTerminal::TManagedTerminal(TSessionData * SessionData,
  30. TConfiguration * Configuration) :
  31. TTerminal(SessionData, Configuration),
  32. LocalBrowser(false), LocalExplorerState(NULL), RemoteExplorerState(NULL), OtherLocalExplorerState(NULL),
  33. ReopenStart(0), DirectoryLoaded(Now()), TerminalThread(NULL), Disconnected(false), DisconnectedTemporarily(false)
  34. {
  35. StateData = new TSessionData(L"");
  36. StateData->Assign(SessionData);
  37. StateData->LocalDirectory = StateData->LocalDirectoryExpanded;
  38. }
  39. //---------------------------------------------------------------------------
  40. __fastcall TManagedTerminal::~TManagedTerminal()
  41. {
  42. delete StateData;
  43. delete LocalExplorerState;
  44. delete OtherLocalExplorerState;
  45. delete RemoteExplorerState;
  46. }
  47. //---------------------------------------------------------------------------
  48. //---------------------------------------------------------------------------
  49. TTerminalManager * __fastcall TTerminalManager::Instance(bool ForceCreation)
  50. {
  51. if (!FInstance && ForceCreation)
  52. {
  53. FInstance = new TTerminalManager();
  54. }
  55. return FInstance;
  56. }
  57. //---------------------------------------------------------------------------
  58. void __fastcall TTerminalManager::DestroyInstance()
  59. {
  60. DebugAssert(FInstance);
  61. SAFE_DESTROY(FInstance);
  62. }
  63. //---------------------------------------------------------------------------
  64. __fastcall TTerminalManager::TTerminalManager() :
  65. TTerminalList(Configuration)
  66. {
  67. FQueueSection = new TCriticalSection();
  68. FActiveSession = NULL;
  69. FTerminalWithFatalExceptionTimer = NULL;
  70. FScpExplorer = NULL;
  71. FDestroying = false;
  72. FTerminalPendingAction = tpNull;
  73. FDirectoryReadingStart = 0;
  74. FAuthenticateForm = NULL;
  75. FTaskbarList = NULL;
  76. FAuthenticating = 0;
  77. FMainThread = GetCurrentThreadId();
  78. FChangeSection.reset(new TCriticalSection());
  79. FPendingConfigurationChange = 0;
  80. FKeepAuthenticateForm = false;
  81. FUpdating = 0;
  82. FApplicationsEvents.reset(new TApplicationEvents(Application));
  83. FApplicationsEvents->OnException = ApplicationException;
  84. FApplicationsEvents->OnShowHint = ApplicationShowHint;
  85. FApplicationsEvents->OnMessage = ApplicationMessage;
  86. FApplicationsEvents->OnModalBegin = ApplicationModalBegin;
  87. FApplicationsEvents->OnModalEnd = ApplicationModalEnd;
  88. DebugAssert(WinConfiguration->OnMasterPasswordPrompt == NULL);
  89. WinConfiguration->OnMasterPasswordPrompt = MasterPasswordPrompt;
  90. InitTaskbarButtonCreatedMessage();
  91. DebugAssert(Configuration && !Configuration->OnChange);
  92. Configuration->OnChange = ConfigurationChange;
  93. FMaxSessions = WinConfiguration->MaxSessions;
  94. FSessionList = new TStringList();
  95. FQueues = new TList();
  96. FTerminationMessages = new TStringList();
  97. std::unique_ptr<TSessionData> DummyData(new TSessionData(L""));
  98. FLocalTerminal = CreateTerminal(DummyData.get());
  99. SetupTerminal(FLocalTerminal);
  100. }
  101. //---------------------------------------------------------------------------
  102. __fastcall TTerminalManager::~TTerminalManager()
  103. {
  104. FreeAll();
  105. DebugAssert(!ScpExplorer);
  106. DebugAssert(Configuration->OnChange == ConfigurationChange);
  107. Configuration->OnChange = NULL;
  108. FApplicationsEvents.reset(NULL);
  109. DebugAssert(WinConfiguration->OnMasterPasswordPrompt == MasterPasswordPrompt);
  110. WinConfiguration->OnMasterPasswordPrompt = NULL;
  111. delete FLocalTerminal;
  112. delete FQueues;
  113. delete FTerminationMessages;
  114. delete FSessionList;
  115. CloseAutheticateForm();
  116. delete FQueueSection;
  117. ReleaseTaskbarList();
  118. }
  119. //---------------------------------------------------------------------------
  120. void __fastcall TTerminalManager::SetQueueConfiguration(TTerminalQueue * Queue)
  121. {
  122. Queue->TransfersLimit = GUIConfiguration->QueueTransfersLimit;
  123. Queue->KeepDoneItemsFor =
  124. (GUIConfiguration->QueueKeepDoneItems ? GUIConfiguration->QueueKeepDoneItemsFor : 0);
  125. }
  126. //---------------------------------------------------------------------------
  127. TTerminalQueue * __fastcall TTerminalManager::NewQueue(TTerminal * Terminal)
  128. {
  129. TTerminalQueue * Queue = new TTerminalQueue(Terminal, Configuration);
  130. SetQueueConfiguration(Queue);
  131. Queue->Enabled = WinConfiguration->EnableQueueByDefault;
  132. Queue->OnQueryUser = TerminalQueryUser;
  133. Queue->OnPromptUser = TerminalPromptUser;
  134. Queue->OnShowExtendedException = TerminalShowExtendedException;
  135. Queue->OnEvent = QueueEvent;
  136. return Queue;
  137. }
  138. //---------------------------------------------------------------------------
  139. TManagedTerminal * __fastcall TTerminalManager::CreateManagedTerminal(TSessionData * Data)
  140. {
  141. TManagedTerminal * Result = new TManagedTerminal(Data, Configuration);
  142. Result->LocalBrowser = Data->IsLocalBrowser;
  143. return Result;
  144. }
  145. //---------------------------------------------------------------------------
  146. TTerminal * __fastcall TTerminalManager::CreateTerminal(TSessionData * Data)
  147. {
  148. return CreateManagedTerminal(Data);
  149. }
  150. //---------------------------------------------------------------------------
  151. TManagedTerminal * __fastcall TTerminalManager::GetSession(int Index)
  152. {
  153. return DebugNotNull(dynamic_cast<TManagedTerminal *>(TTerminalList::Terminals[Index]));
  154. }
  155. //---------------------------------------------------------------------------
  156. void __fastcall TTerminalManager::SetupTerminal(TTerminal * Terminal)
  157. {
  158. Terminal->OnQueryUser = TerminalQueryUser;
  159. Terminal->OnPromptUser = TerminalPromptUser;
  160. Terminal->OnDisplayBanner = TerminalDisplayBanner;
  161. Terminal->OnShowExtendedException = TerminalShowExtendedException;
  162. Terminal->OnProgress = OperationProgress;
  163. Terminal->OnFinished = OperationFinished;
  164. Terminal->OnDeleteLocalFile = DeleteLocalFile;
  165. Terminal->OnReadDirectoryProgress = TerminalReadDirectoryProgress;
  166. Terminal->OnInformation = TerminalInformation;
  167. Terminal->OnCustomCommand = TerminalCustomCommand;
  168. }
  169. //---------------------------------------------------------------------------
  170. TManagedTerminal * __fastcall TTerminalManager::DoNewSession(TSessionData * Data)
  171. {
  172. if (Count >= FMaxSessions)
  173. {
  174. UnicodeString Msg = FMTLOAD(TOO_MANY_SESSIONS, (Count));
  175. if (MessageDialog(Msg, qtConfirmation, qaOK | qaCancel, HELP_TOO_MANY_SESSIONS) == qaCancel)
  176. {
  177. Abort();
  178. }
  179. FMaxSessions = FMaxSessions * 3 / 2; // increase limit before the next warning by 50%
  180. }
  181. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(TTerminalList::NewTerminal(Data)));
  182. try
  183. {
  184. FQueues->Add(NewQueue(Session));
  185. FTerminationMessages->Add(L"");
  186. SetupTerminal(Session);
  187. }
  188. catch(...)
  189. {
  190. if (Session != NULL)
  191. {
  192. FreeTerminal(Session);
  193. }
  194. throw;
  195. }
  196. return Session;
  197. }
  198. //---------------------------------------------------------------------------
  199. TTerminal * __fastcall TTerminalManager::NewTerminal(TSessionData * Data)
  200. {
  201. TTerminal * Terminal = DoNewSession(Data);
  202. DoSessionListChanged();
  203. return Terminal;
  204. }
  205. //---------------------------------------------------------------------------
  206. TManagedTerminal * __fastcall TTerminalManager::NewLocalBrowser(const UnicodeString & LocalDirectory, const UnicodeString & OtherLocalDirectory)
  207. {
  208. std::unique_ptr<TSessionData> SessionData(new TSessionData(UnicodeString()));
  209. SessionData->LocalDirectory = LocalDirectory;
  210. SessionData->OtherLocalDirectory = OtherLocalDirectory;
  211. TManagedTerminal * Result = NewManagedTerminal(SessionData.get());
  212. // Is true already, when LocalDirectory and OtherLocalDirectory are set
  213. Result->LocalBrowser = true;
  214. return Result;
  215. }
  216. //---------------------------------------------------------------------------
  217. void TTerminalManager::NewLocalSession(const UnicodeString & LocalDirectory, const UnicodeString & OtherLocalDirectory)
  218. {
  219. ActiveSession = NewLocalBrowser(LocalDirectory, OtherLocalDirectory);
  220. }
  221. //---------------------------------------------------------------------------
  222. TManagedTerminal * __fastcall TTerminalManager::NewManagedTerminal(TSessionData * Data)
  223. {
  224. return DebugNotNull(dynamic_cast<TManagedTerminal *>(NewTerminal(Data)));
  225. }
  226. //---------------------------------------------------------------------------
  227. bool TTerminalManager::SupportedSession(TSessionData * Data)
  228. {
  229. bool Result;
  230. // When main window exists already, ask it if it supports the session
  231. // (we cannot decide based on configuration,
  232. // as the user might have changed the interface in the preferences after the main window was created)
  233. // If not, assume based on configuration.
  234. if (ScpExplorer != NULL)
  235. {
  236. Result = ScpExplorer->SupportedSession(Data);
  237. }
  238. else
  239. {
  240. Result =
  241. (WinConfiguration->Interface != ifExplorer) ||
  242. !Data->IsLocalBrowser;
  243. }
  244. return Result;
  245. }
  246. //---------------------------------------------------------------------------
  247. TManagedTerminal * __fastcall TTerminalManager::NewSessions(TList * DataList)
  248. {
  249. TManagedTerminal * Result = NULL;
  250. for (int Index = 0; Index < DataList->Count; Index++)
  251. {
  252. TSessionData * Data = reinterpret_cast<TSessionData *>(DataList->Items[Index]);
  253. if (SupportedSession(Data))
  254. {
  255. TManagedTerminal * Session = DoNewSession(Data);
  256. // When opening workspace/folder, keep the sessions open, even if they fail to connect.
  257. // We cannot detect a folder here, so we "guess" it by a session set size.
  258. // After all, no one will have a folder with a one session only (while a workspace with one session is likely).
  259. // And when when opening a folder with a one session only, it's not that big problem, if we treat it the same way
  260. // as when opening the session only.
  261. // Also closing a workspace session will remove the session from the workspace.
  262. // While closing a folder session won't remove the session from the folder.
  263. Session->Permanent = Data->IsWorkspace || (DataList->Count > 1);
  264. if (Result == NULL)
  265. {
  266. Result = Session;
  267. }
  268. }
  269. }
  270. DoSessionListChanged();
  271. return Result;
  272. }
  273. //---------------------------------------------------------------------------
  274. void __fastcall TTerminalManager::FreeActiveTerminal()
  275. {
  276. if (FTerminalPendingAction == tpNull)
  277. {
  278. DebugAssert(ActiveSession != NULL);
  279. FreeTerminal(ActiveSession);
  280. }
  281. else
  282. {
  283. DebugAssert(FTerminalPendingAction == ::tpNone);
  284. FTerminalPendingAction = tpFree;
  285. }
  286. }
  287. //---------------------------------------------------------------------------
  288. void __fastcall TTerminalManager::DoConnectTerminal(TTerminal * Terminal, bool Reopen, bool AdHoc)
  289. {
  290. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  291. // it must be managed terminal, unless it is secondary terminal (of managed terminal)
  292. DebugAssert((ManagedTerminal != NULL) || (dynamic_cast<TSecondaryTerminal *>(Terminal) != NULL));
  293. // particularly when we are reconnecting RemoteDirectory of managed terminal
  294. // hold the last used remote directory as opposite to session data, which holds
  295. // the default remote directory.
  296. // make sure the last used directory is used, but the default is preserved too
  297. UnicodeString OrigRemoteDirectory = Terminal->SessionData->RemoteDirectory;
  298. try
  299. {
  300. TTerminalThread * TerminalThread = new TTerminalThread(Terminal);
  301. TerminalThread->AllowAbandon = (Terminal == ActiveTerminal);
  302. try
  303. {
  304. if (ManagedTerminal != NULL)
  305. {
  306. Terminal->SessionData->RemoteDirectory = ManagedTerminal->StateData->RemoteDirectory;
  307. if ((double)ManagedTerminal->ReopenStart == 0)
  308. {
  309. ManagedTerminal->ReopenStart = Now();
  310. }
  311. ManagedTerminal->Disconnected = false;
  312. ManagedTerminal->DisconnectedTemporarily = false;
  313. DebugAssert(ManagedTerminal->TerminalThread == NULL);
  314. ManagedTerminal->TerminalThread = TerminalThread;
  315. }
  316. TNotifyEvent OnIdle;
  317. ((TMethod*)&OnIdle)->Code = TerminalThreadIdle;
  318. TerminalThread->OnIdle = OnIdle;
  319. if (Reopen)
  320. {
  321. TerminalThread->TerminalReopen();
  322. }
  323. else
  324. {
  325. TerminalThread->TerminalOpen();
  326. }
  327. }
  328. __finally
  329. {
  330. TerminalThread->OnIdle = NULL;
  331. if (!TerminalThread->Release())
  332. {
  333. if (!AdHoc && (DebugAlwaysTrue(Terminal == ActiveTerminal)))
  334. {
  335. // terminal was abandoned, must create a new one to replace it
  336. Terminal = ManagedTerminal = CreateManagedTerminal(new TSessionData(L""));
  337. SetupTerminal(Terminal);
  338. OwnsObjects = false;
  339. Items[ActiveSessionIndex] = Terminal;
  340. OwnsObjects = true;
  341. FActiveSession = ManagedTerminal;
  342. // Can be NULL, when opening the first session from command-line
  343. if (FScpExplorer != NULL)
  344. {
  345. FScpExplorer->ReplaceTerminal(ManagedTerminal);
  346. }
  347. }
  348. // Now we do not have any reference to an abandoned terminal, so we can safely allow the thread
  349. // to complete its task and destroy the terminal afterwards.
  350. TerminalThread->Terminate();
  351. // When abandoning cancelled terminal, DoInformation(Phase = 0) does not make it to TerminalInformation handler.
  352. if (DebugAlwaysTrue(FAuthenticating > 0))
  353. {
  354. FKeepAuthenticateForm = false;
  355. AuthenticatingDone();
  356. }
  357. }
  358. else
  359. {
  360. if (ManagedTerminal != NULL)
  361. {
  362. ManagedTerminal->TerminalThread = NULL;
  363. }
  364. }
  365. }
  366. }
  367. __finally
  368. {
  369. Terminal->SessionData->RemoteDirectory = OrigRemoteDirectory;
  370. if (Terminal->Active && (ManagedTerminal != NULL))
  371. {
  372. ManagedTerminal->ReopenStart = 0;
  373. ManagedTerminal->Permanent = true;
  374. }
  375. }
  376. if (DebugAlwaysTrue(Terminal->Active) && !Reopen && GUIConfiguration->QueueBootstrap)
  377. {
  378. FindQueueForTerminal(Terminal)->AddItem(new TBootstrapQueueItem());
  379. }
  380. }
  381. //---------------------------------------------------------------------------
  382. void __fastcall TTerminalManager::CloseAutheticateForm()
  383. {
  384. SAFE_DESTROY(FAuthenticateForm);
  385. }
  386. //---------------------------------------------------------------------------
  387. bool __fastcall TTerminalManager::ConnectTerminal(TTerminal * Terminal)
  388. {
  389. bool Result = true;
  390. // were it an active terminal, it would allow abandoning, what this API cannot deal with
  391. DebugAssert(Terminal != ActiveTerminal);
  392. try
  393. {
  394. DoConnectTerminal(Terminal, false, false);
  395. }
  396. catch (Exception & E)
  397. {
  398. ShowExtendedExceptionEx(Terminal, &E);
  399. Result = false;
  400. }
  401. return Result;
  402. }
  403. //---------------------------------------------------------------------------
  404. void __fastcall TTerminalManager::TerminalThreadIdle(void * /*Data*/, TObject * /*Sender*/)
  405. {
  406. Application->ProcessMessages();
  407. }
  408. //---------------------------------------------------------------------------
  409. bool __fastcall TTerminalManager::ConnectActiveTerminalImpl(bool Reopen)
  410. {
  411. ActiveTerminal->CollectUsage();
  412. TTerminalPendingAction Action;
  413. bool Result;
  414. do
  415. {
  416. Action = tpNull;
  417. Result = false;
  418. try
  419. {
  420. DebugAssert(ActiveTerminal != NULL);
  421. DoConnectTerminal(ActiveTerminal, Reopen, false);
  422. if (ScpExplorer)
  423. {
  424. DebugAssert(ActiveTerminal->Status == ssOpened);
  425. SessionReady();
  426. }
  427. WinConfiguration->ClearTemporaryLoginData();
  428. Result = true;
  429. }
  430. catch (Exception & E)
  431. {
  432. DebugAssert(FTerminalPendingAction == tpNull);
  433. FTerminalPendingAction = ::tpNone;
  434. try
  435. {
  436. DebugAssert(ActiveTerminal != NULL);
  437. ActiveTerminal->ShowExtendedException(&E);
  438. Action = FTerminalPendingAction;
  439. }
  440. __finally
  441. {
  442. FTerminalPendingAction = tpNull;
  443. }
  444. }
  445. }
  446. while (Action == tpReconnect);
  447. if (Action == tpFree)
  448. {
  449. DisconnectActiveTerminalIfPermanentFreeOtherwise();
  450. }
  451. return Result;
  452. }
  453. //---------------------------------------------------------------------------
  454. void __fastcall TTerminalManager::DisconnectActiveTerminalIfPermanentFreeOtherwise()
  455. {
  456. if (ActiveTerminal->Permanent)
  457. {
  458. DisconnectActiveTerminal();
  459. }
  460. else
  461. {
  462. FreeActiveTerminal();
  463. }
  464. }
  465. //---------------------------------------------------------------------------
  466. bool __fastcall TTerminalManager::ConnectActiveTerminal()
  467. {
  468. // add only stored sessions to the jump list,
  469. // ad-hoc session cannot be reproduced from just a session name
  470. if (StoredSessions->FindSame(ActiveTerminal->SessionData) != NULL)
  471. {
  472. try
  473. {
  474. WinConfiguration->AddSessionToJumpList(ActiveTerminal->SessionData->SessionName);
  475. }
  476. catch (Exception & E)
  477. {
  478. ShowExtendedException(&E);
  479. }
  480. }
  481. FAuthenticationCancelled = false;
  482. bool Result = ConnectActiveTerminalImpl(false);
  483. UnicodeString DateStamp = StandardDatestamp();
  484. if (Result)
  485. {
  486. if (Configuration->Usage->Get(L"OpenedSessionsFailedLastDate") == DateStamp)
  487. {
  488. Configuration->Usage->Inc(L"OpenedSessionsFailedRecovered");
  489. }
  490. }
  491. else
  492. {
  493. Configuration->Usage->Inc(L"OpenedSessionsFailed");
  494. Configuration->Usage->Set(L"OpenedSessionsFailedLastDate", DateStamp);
  495. if (FAuthenticationCancelled)
  496. {
  497. Configuration->Usage->Inc(L"OpenedSessionsFailedAfterCancel");
  498. }
  499. }
  500. if (Result && WinConfiguration->AutoOpenInPutty && CanOpenInPutty())
  501. {
  502. try
  503. {
  504. OpenInPutty();
  505. }
  506. catch(Exception & E)
  507. {
  508. ShowExtendedExceptionEx(NULL, &E);
  509. }
  510. }
  511. return Result;
  512. }
  513. //---------------------------------------------------------------------------
  514. void __fastcall TTerminalManager::DisconnectActiveTerminal()
  515. {
  516. DebugAssert(ActiveTerminal);
  517. if (ActiveTerminal->Active)
  518. {
  519. ActiveTerminal->Close();
  520. }
  521. int Index = IndexOf(ActiveTerminal);
  522. TTerminalQueue * OldQueue;
  523. TTerminalQueue * NewQueue;
  524. OldQueue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  525. NewQueue = this->NewQueue(ActiveTerminal);
  526. FQueues->Items[Index] = NewQueue;
  527. if (ScpExplorer != NULL)
  528. {
  529. ScpExplorer->Queue = NewQueue;
  530. }
  531. delete OldQueue;
  532. ActiveTerminal->Disconnected = true;
  533. if (ScpExplorer != NULL)
  534. {
  535. SessionReady(); // in case it was never connected
  536. ScpExplorer->TerminalDisconnected();
  537. }
  538. // disconnecting duplidate session removes need to distinguish the only connected session with short path
  539. DoSessionListChanged();
  540. }
  541. //---------------------------------------------------------------------------
  542. void __fastcall TTerminalManager::ReconnectActiveTerminal()
  543. {
  544. DebugAssert(ActiveTerminal);
  545. if (ScpExplorer)
  546. {
  547. if (ScpExplorer->Terminal == ActiveTerminal)
  548. {
  549. ScpExplorer->UpdateSession(ActiveTerminal);
  550. }
  551. }
  552. try
  553. {
  554. if (FTerminalPendingAction == tpNull)
  555. {
  556. ConnectActiveTerminalImpl(true);
  557. }
  558. else
  559. {
  560. FTerminalPendingAction = tpReconnect;
  561. }
  562. }
  563. catch(...)
  564. {
  565. DisconnectActiveTerminal();
  566. throw;
  567. }
  568. }
  569. //---------------------------------------------------------------------------
  570. void __fastcall TTerminalManager::FreeAll()
  571. {
  572. FDestroying = true;
  573. try
  574. {
  575. while (Count)
  576. {
  577. FreeTerminal(Sessions[0]);
  578. }
  579. }
  580. __finally
  581. {
  582. FDestroying = false;
  583. }
  584. }
  585. //---------------------------------------------------------------------------
  586. void __fastcall TTerminalManager::FreeTerminal(TTerminal * Terminal)
  587. {
  588. try
  589. {
  590. TManagedTerminal * ManagedSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  591. // we want the Login dialog to open on auto-workspace name,
  592. // as set in TCustomScpExplorerForm::FormClose
  593. if ((!FDestroying || !WinConfiguration->AutoSaveWorkspace) && !ManagedSession->LocalBrowser)
  594. {
  595. if (StoredSessions->FindSame(Terminal->SessionData) != NULL)
  596. {
  597. WinConfiguration->LastStoredSession = Terminal->SessionData->Name;
  598. }
  599. }
  600. if (ScpExplorer != NULL)
  601. {
  602. ScpExplorer->TerminalRemoved(Terminal);
  603. }
  604. if (Terminal->Active)
  605. {
  606. Terminal->Close();
  607. }
  608. }
  609. __finally
  610. {
  611. int Index = IndexOf(Terminal);
  612. Extract(Terminal);
  613. TTerminalQueue * Queue;
  614. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  615. FQueues->Delete(Index);
  616. FTerminationMessages->Delete(Index);
  617. if ((ActiveSession != NULL) && (Terminal == ActiveSession))
  618. {
  619. TManagedTerminal * NewActiveTerminal;
  620. bool LastTerminalClosed = false;
  621. if (FDestroying)
  622. {
  623. NewActiveTerminal = NULL;
  624. }
  625. else
  626. {
  627. if (Count > 0)
  628. {
  629. NewActiveTerminal = Sessions[Index < Count ? Index : Index - 1];
  630. if (!NewActiveTerminal->Active && !NewActiveTerminal->Disconnected)
  631. {
  632. NewActiveTerminal->Disconnected = true;
  633. NewActiveTerminal->DisconnectedTemporarily = true;
  634. }
  635. }
  636. else
  637. {
  638. NewActiveTerminal = NULL;
  639. LastTerminalClosed = true;
  640. if (ScpExplorer != NULL)
  641. {
  642. TAutoNestingCounter UpdatingCounter(FUpdating); // prevent tab flicker
  643. NewActiveTerminal = ScpExplorer->GetReplacementForLastSession();
  644. }
  645. }
  646. }
  647. DoSetActiveSession(NewActiveTerminal, false, LastTerminalClosed);
  648. }
  649. else
  650. {
  651. SaveTerminal(Terminal);
  652. }
  653. // only now all references to/from queue (particularly events to explorer)
  654. // are cleared
  655. delete Queue;
  656. delete Terminal;
  657. DoSessionListChanged();
  658. }
  659. }
  660. //---------------------------------------------------------------------------
  661. void TTerminalManager::UpdateScpExplorer(TManagedTerminal * Session, TTerminalQueue * Queue)
  662. {
  663. FScpExplorer->ManagedSession = Session;
  664. FScpExplorer->Queue = Queue;
  665. }
  666. //---------------------------------------------------------------------------
  667. void TTerminalManager::UpdateScpExplorer()
  668. {
  669. UpdateScpExplorer(ActiveSession, ActiveQueue);
  670. }
  671. //---------------------------------------------------------------------------
  672. void __fastcall TTerminalManager::SetScpExplorer(TCustomScpExplorerForm * value)
  673. {
  674. if (ScpExplorer != value)
  675. {
  676. // changing explorer is not supported yet
  677. DebugAssert(!ScpExplorer || !value);
  678. FScpExplorer = value;
  679. if (FScpExplorer)
  680. {
  681. UpdateScpExplorer();
  682. UpdateTaskbarList();
  683. }
  684. }
  685. }
  686. //---------------------------------------------------------------------------
  687. TManagedTerminal * TTerminalManager::GetActiveTerminal()
  688. {
  689. TManagedTerminal * Result;
  690. if ((ActiveSession != NULL) && !ActiveSession->LocalBrowser)
  691. {
  692. Result = ActiveSession;
  693. }
  694. else
  695. {
  696. Result = NULL;
  697. }
  698. return Result;
  699. }
  700. //---------------------------------------------------------------------------
  701. void __fastcall TTerminalManager::SetActiveSession(TManagedTerminal * value)
  702. {
  703. DoSetActiveSession(value, false, false);
  704. }
  705. //---------------------------------------------------------------------------
  706. void __fastcall TTerminalManager::SetActiveTerminalWithAutoReconnect(TManagedTerminal * value)
  707. {
  708. DoSetActiveSession(value, true, false);
  709. }
  710. //---------------------------------------------------------------------------
  711. void __fastcall TTerminalManager::DoSetActiveSession(TManagedTerminal * value, bool AutoReconnect, bool LastTerminalClosed)
  712. {
  713. if (ActiveSession != value)
  714. {
  715. if (NonVisualDataModule != NULL)
  716. {
  717. NonVisualDataModule->StartBusy();
  718. }
  719. try
  720. {
  721. // here used to be call to TCustomScpExporer::UpdateSessionData (now UpdateSession)
  722. // but it seems to be duplicate to call from TCustomScpExporer::SessionChanging
  723. TManagedTerminal * PActiveSession = ActiveSession;
  724. FActiveSession = value;
  725. if (ScpExplorer)
  726. {
  727. if ((ActiveSession != NULL) &&
  728. ((ActiveSession->Status == ssOpened) || ActiveSession->Disconnected || ActiveSession->LocalBrowser))
  729. {
  730. SessionReady();
  731. }
  732. else
  733. {
  734. UpdateScpExplorer(NULL, NULL);
  735. }
  736. }
  737. UpdateAppTitle();
  738. if (PActiveSession != NULL)
  739. {
  740. if (PActiveSession->DisconnectedTemporarily && DebugAlwaysTrue(PActiveSession->Disconnected))
  741. {
  742. PActiveSession->Disconnected = false;
  743. PActiveSession->DisconnectedTemporarily = false;
  744. }
  745. if (!PActiveSession->Active)
  746. {
  747. SaveTerminal(PActiveSession);
  748. }
  749. }
  750. if (ActiveSession != NULL)
  751. {
  752. int Index = ActiveSessionIndex;
  753. if (!ActiveSession->Active &&
  754. !FTerminationMessages->Strings[Index].IsEmpty() &&
  755. DebugAlwaysTrue(!ActiveSession->LocalBrowser))
  756. {
  757. UnicodeString Message = FTerminationMessages->Strings[Index];
  758. FTerminationMessages->Strings[Index] = L"";
  759. if (AutoReconnect)
  760. {
  761. ReconnectActiveTerminal();
  762. }
  763. else
  764. {
  765. Exception * E = new ESshFatal(NULL, Message);
  766. try
  767. {
  768. // finally show pending terminal message,
  769. // this gives user also possibility to reconnect
  770. ActiveTerminal->ShowExtendedException(E);
  771. }
  772. __finally
  773. {
  774. delete E;
  775. }
  776. }
  777. }
  778. // LastTerminalClosed is true only for a replacement local session,
  779. // and it should never happen that it fails to be activated
  780. if (LastTerminalClosed && DebugAlwaysFalse(value != ActiveSession))
  781. {
  782. LastTerminalClosed = false; // just in case
  783. }
  784. }
  785. else
  786. {
  787. LastTerminalClosed = true;
  788. }
  789. if (LastTerminalClosed && !Updating && (ScpExplorer != NULL))
  790. {
  791. ScpExplorer->LastTerminalClosed();
  792. }
  793. if ((ActiveSession != NULL) &&
  794. !ActiveSession->Active && !ActiveSession->Disconnected && !ActiveSession->LocalBrowser)
  795. {
  796. ConnectActiveTerminal();
  797. }
  798. }
  799. __finally
  800. {
  801. if (NonVisualDataModule != NULL)
  802. {
  803. NonVisualDataModule->EndBusy();
  804. }
  805. }
  806. }
  807. }
  808. //---------------------------------------------------------------------------
  809. void __fastcall TTerminalManager::QueueStatusUpdated()
  810. {
  811. UpdateAppTitle();
  812. }
  813. //---------------------------------------------------------------------------
  814. bool __fastcall TTerminalManager::ShouldDisplayQueueStatusOnAppTitle()
  815. {
  816. bool Result = IsApplicationMinimized();
  817. if (!Result && (ScpExplorer != NULL))
  818. {
  819. HWND Window = GetActiveWindow();
  820. Window = GetAncestor(Window, GA_ROOTOWNER);
  821. Result = (ScpExplorer->Handle != Window);
  822. }
  823. return Result;
  824. }
  825. //---------------------------------------------------------------------------
  826. UnicodeString __fastcall TTerminalManager::FormatFormCaptionWithSession(TCustomForm * Form, const UnicodeString & Caption)
  827. {
  828. return FormatFormCaption(Form, Caption, GetActiveSessionAppTitle());
  829. }
  830. //---------------------------------------------------------------------------
  831. UnicodeString __fastcall TTerminalManager::GetAppProgressTitle()
  832. {
  833. UnicodeString Result;
  834. UnicodeString QueueProgressTitle;
  835. UnicodeString ProgressTitle = !FProgressTitle.IsEmpty() ? FProgressTitle : ScpExplorer->GetProgressTitle();
  836. if (!FForegroundProgressTitle.IsEmpty())
  837. {
  838. Result = FForegroundProgressTitle;
  839. }
  840. else if (!ProgressTitle.IsEmpty() && !ForegroundTask())
  841. {
  842. Result = ProgressTitle;
  843. }
  844. else if (ShouldDisplayQueueStatusOnAppTitle() &&
  845. !(QueueProgressTitle = ScpExplorer->GetQueueProgressTitle()).IsEmpty())
  846. {
  847. Result = QueueProgressTitle;
  848. }
  849. return Result;
  850. }
  851. //---------------------------------------------------------------------------
  852. void __fastcall TTerminalManager::UpdateAppTitle()
  853. {
  854. if (ScpExplorer)
  855. {
  856. TForm * MainForm = GetMainForm();
  857. if (MainForm != ScpExplorer)
  858. {
  859. // triggers caption update for some forms
  860. MainForm->Perform(WM_MANAGES_CAPTION, 0, 0);
  861. }
  862. UnicodeString NewTitle = FormatMainFormCaption(GetActiveSessionAppTitle());
  863. UnicodeString ProgressTitle = GetAppProgressTitle();
  864. if (!ProgressTitle.IsEmpty())
  865. {
  866. NewTitle = ProgressTitle + TitleSeparator + NewTitle;
  867. }
  868. else if (ScpExplorer != NULL)
  869. {
  870. UnicodeString Path = ScpExplorer->PathForCaption();
  871. if (!Path.IsEmpty())
  872. {
  873. NewTitle = Path + TitleSeparator + NewTitle;
  874. }
  875. }
  876. // Not updating MainForm here, as for all other possible main forms, this code is actually not what we want.
  877. // And they all update their title on their own (some using GetAppProgressTitle()).
  878. ScpExplorer->Caption = NewTitle;
  879. ScpExplorer->ApplicationTitleChanged();
  880. }
  881. }
  882. //---------------------------------------------------------------------------
  883. void __fastcall TTerminalManager::SaveTerminal(TTerminal * Terminal)
  884. {
  885. TSessionData * Data = StoredSessions->FindSame(Terminal->SessionData);
  886. if (Data != NULL)
  887. {
  888. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  889. DebugAssert(ManagedTerminal != NULL);
  890. bool Changed = false;
  891. if (Terminal->SessionData->UpdateDirectories)
  892. {
  893. Data->CopyDirectoriesStateData(ManagedTerminal->StateData);
  894. Changed = true;
  895. }
  896. if (Changed)
  897. {
  898. // modified only, implicit
  899. StoredSessions->Save(false, false);
  900. }
  901. }
  902. }
  903. //---------------------------------------------------------------------------
  904. void __fastcall TTerminalManager::HandleException(Exception * E)
  905. {
  906. // can be null for example when exception is thrown on login dialog
  907. if (ActiveTerminal != NULL)
  908. {
  909. ActiveTerminal->ShowExtendedException(E);
  910. }
  911. else
  912. {
  913. ShowExtendedException(E);
  914. }
  915. }
  916. //---------------------------------------------------------------------------
  917. void __fastcall TTerminalManager::ApplicationException(TObject * /*Sender*/,
  918. Exception * E)
  919. {
  920. HandleException(E);
  921. }
  922. //---------------------------------------------------------------------------
  923. void __fastcall TTerminalManager::ApplicationShowHint(UnicodeString & HintStr,
  924. bool & /*CanShow*/, THintInfo & HintInfo)
  925. {
  926. HintInfo.HintData = HintInfo.HintControl;
  927. if (HasLabelHintPopup(HintInfo.HintControl, HintStr))
  928. {
  929. // Hack for transfer setting labels.
  930. // Should be converted to something like HintLabel()
  931. HintInfo.HideTimeout = 100000; // "almost" never
  932. }
  933. else if (dynamic_cast<TProgressBar *>(HintInfo.HintControl) != NULL)
  934. {
  935. // Hint is forcibly hidden in TProgressForm::FormHide
  936. HintInfo.HideTimeout = 100000; // "almost" never
  937. HintInfo.ReshowTimeout = 500; // updated each 0.5s
  938. }
  939. else
  940. {
  941. int HintMaxWidth = 300;
  942. TControl * ScaleControl = HintInfo.HintControl;
  943. if (DebugAlwaysFalse(HintInfo.HintControl == NULL) ||
  944. (GetParentForm(HintInfo.HintControl) == NULL))
  945. {
  946. ScaleControl = ScpExplorer;
  947. }
  948. HintMaxWidth = ScaleByTextHeight(ScaleControl, HintMaxWidth);
  949. HintInfo.HintMaxWidth = HintMaxWidth;
  950. }
  951. }
  952. //---------------------------------------------------------------------------
  953. bool __fastcall TTerminalManager::HandleMouseWheel(WPARAM WParam, LPARAM LParam)
  954. {
  955. // WORKAROUND This is no longer necessary on Windows 10 (except for WM_WANTS_MOUSEWHEEL_INACTIVE part)
  956. bool Result = false;
  957. if (Application->Active)
  958. {
  959. TPoint Point(LOWORD(LParam), HIWORD(LParam));
  960. TWinControl * Control = FindVCLWindow(Point);
  961. if (Control != NULL)
  962. {
  963. TCustomForm * Form = GetParentForm(Control);
  964. // Only case we expect the parent form to be NULL is on the Find/Replace dialog,
  965. // which is owned by VCL's internal TRedirectorWindow.
  966. DebugAssert((Form != NULL) || (Control->ClassName() == L"TRedirectorWindow"));
  967. if (Form != NULL)
  968. {
  969. // Send it only to windows we tested it with.
  970. // Though we should sooner or later remove this test and pass it to all our windows.
  971. if (Form->Active && (Form->Perform(WM_WANTS_MOUSEWHEEL, 0, 0) == 1))
  972. {
  973. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  974. Result = true;
  975. }
  976. else if (!Form->Active && (Form->Perform(WM_WANTS_MOUSEWHEEL_INACTIVE, 0, 0) == 1))
  977. {
  978. TWinControl * Control2;
  979. // FindVCLWindow stops on window level, when the window is not active? or when there's a modal window over it?
  980. // (but in any case, when we have operation running on top of Synchronization checklist).
  981. // WORKAROUND: The while loop does what AllLevels parameter of ControlAtPos should do, but it's broken.
  982. // Based on (now removed) Embarcadero QC 82143.
  983. while ((Control2 = dynamic_cast<TWinControl *>(Control->ControlAtPos(Control->ScreenToClient(Point), false, true))) != NULL)
  984. {
  985. Control = Control2;
  986. }
  987. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  988. Result = true;
  989. }
  990. }
  991. }
  992. }
  993. return Result;
  994. }
  995. //---------------------------------------------------------------------------
  996. void __fastcall TTerminalManager::ApplicationMessage(TMsg & Msg, bool & Handled)
  997. {
  998. if (Msg.message == FTaskbarButtonCreatedMessage)
  999. {
  1000. CreateTaskbarList();
  1001. }
  1002. if (Msg.message == WM_MOUSEWHEEL)
  1003. {
  1004. Handled = HandleMouseWheel(Msg.wParam, Msg.lParam);
  1005. }
  1006. }
  1007. //---------------------------------------------------------------------------
  1008. void __fastcall TTerminalManager::ApplicationModalBegin(TObject * /*Sender*/)
  1009. {
  1010. InterfaceStartDontMeasure();
  1011. NonVisualDataModule->StartBusy();
  1012. if (ScpExplorer != NULL)
  1013. {
  1014. ScpExplorer->SuspendWindowLock();
  1015. }
  1016. }
  1017. //---------------------------------------------------------------------------
  1018. void __fastcall TTerminalManager::ApplicationModalEnd(TObject * /*Sender*/)
  1019. {
  1020. NonVisualDataModule->EndBusy();
  1021. if (ScpExplorer != NULL)
  1022. {
  1023. ScpExplorer->ResumeWindowLock();
  1024. }
  1025. }
  1026. //---------------------------------------------------------------------------
  1027. void __fastcall TTerminalManager::InitTaskbarButtonCreatedMessage()
  1028. {
  1029. // XE6 VCL already handles TaskbarButtonCreated, but does not call ChangeWindowMessageFilterEx.
  1030. // So we keep our implementation.
  1031. // See also https://stackoverflow.com/q/14614823/850848#14618587
  1032. FTaskbarButtonCreatedMessage = RegisterWindowMessage(L"TaskbarButtonCreated");
  1033. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  1034. ChangeWindowMessageFilterExProc ChangeWindowMessageFilterEx =
  1035. (ChangeWindowMessageFilterExProc)GetProcAddress(User32Library, "ChangeWindowMessageFilterEx");
  1036. if (ChangeWindowMessageFilterEx != NULL)
  1037. {
  1038. // without this we won't get TaskbarButtonCreated, when app is running elevated
  1039. ChangeWindowMessageFilterEx(
  1040. Application->Handle, FTaskbarButtonCreatedMessage, MSGFLT_ALLOW, NULL);
  1041. }
  1042. }
  1043. //---------------------------------------------------------------------------
  1044. void __fastcall TTerminalManager::CreateTaskbarList()
  1045. {
  1046. ReleaseTaskbarList();
  1047. if(SUCCEEDED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL,
  1048. IID_ITaskbarList3, (void **) &FTaskbarList)))
  1049. {
  1050. if (ScpExplorer != NULL)
  1051. {
  1052. UpdateTaskbarList();
  1053. }
  1054. }
  1055. }
  1056. //---------------------------------------------------------------------------
  1057. void __fastcall TTerminalManager::ReleaseTaskbarList()
  1058. {
  1059. if (FTaskbarList != NULL)
  1060. {
  1061. FTaskbarList->Release();
  1062. }
  1063. }
  1064. //---------------------------------------------------------------------------
  1065. void __fastcall TTerminalManager::UpdateTaskbarList()
  1066. {
  1067. ScpExplorer->UpdateTaskbarList(FTaskbarList);
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. void __fastcall TTerminalManager::DeleteLocalFile(const UnicodeString FileName, bool Alternative, int & Deleted)
  1071. {
  1072. Deleted = RecursiveDeleteFileChecked(FileName, (WinConfiguration->DeleteToRecycleBin != Alternative));
  1073. }
  1074. //---------------------------------------------------------------------------
  1075. void __fastcall TTerminalManager::TerminalQueryUser(TObject * Sender,
  1076. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  1077. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * /*Arg*/)
  1078. {
  1079. UnicodeString HelpKeyword;
  1080. TMessageParams MessageParams(Params);
  1081. UnicodeString AQuery = Query;
  1082. if (Params != NULL)
  1083. {
  1084. HelpKeyword = Params->HelpKeyword;
  1085. if (FLAGSET(Params->Params, qpFatalAbort))
  1086. {
  1087. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  1088. if (!MessageParams.TimerMessage.IsEmpty())
  1089. {
  1090. MessageParams.TimerMessage = FMTLOAD(WARN_FATAL_ERROR, (MessageParams.TimerMessage));
  1091. }
  1092. }
  1093. }
  1094. if (ScpExplorer)
  1095. {
  1096. Answer = ScpExplorer->MoreMessageDialog(AQuery, MoreMessages, Type, Answers,
  1097. HelpKeyword, &MessageParams, dynamic_cast<TTerminal *>(Sender));
  1098. }
  1099. else
  1100. {
  1101. Answer = MoreMessageDialog(AQuery, MoreMessages, Type, Answers, HelpKeyword,
  1102. &MessageParams);
  1103. }
  1104. }
  1105. //---------------------------------------------------------------------------
  1106. void __fastcall TTerminalManager::AuthenticateFormCancel(TObject * Sender)
  1107. {
  1108. TAuthenticateForm * Form = dynamic_cast<TAuthenticateForm *>(Sender);
  1109. DebugAssert(Form != NULL);
  1110. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Form->Terminal);
  1111. // will be null e.g. for background transfers
  1112. if (ManagedTerminal != NULL)
  1113. {
  1114. TTerminalThread * TerminalThread = ManagedTerminal->TerminalThread;
  1115. // can be NULL for reconnects from transfers
  1116. if ((TerminalThread != NULL) && !TerminalThread->Cancelling)
  1117. {
  1118. Form->Log(LoadStr(AUTH_CANCELLING));
  1119. TerminalThread->Cancel();
  1120. }
  1121. }
  1122. FAuthenticationCancelled = true;
  1123. }
  1124. //---------------------------------------------------------------------------
  1125. TAuthenticateForm * __fastcall TTerminalManager::MakeAuthenticateForm(
  1126. TTerminal * Terminal)
  1127. {
  1128. TAuthenticateForm * Dialog = SafeFormCreate<TAuthenticateForm>();
  1129. Dialog->Init(Terminal);
  1130. DebugAssert(Dialog->OnCancel == NULL);
  1131. Dialog->OnCancel = AuthenticateFormCancel;
  1132. return Dialog;
  1133. }
  1134. //---------------------------------------------------------------------------
  1135. void __fastcall TTerminalManager::FileNameInputDialogInitializeRenameBaseName(
  1136. TObject * /*Sender*/, TInputDialogData * Data)
  1137. {
  1138. EditSelectBaseName(Data->Edit->Handle);
  1139. }
  1140. //---------------------------------------------------------------------------
  1141. void __fastcall TTerminalManager::TerminalPromptUser(
  1142. TTerminal * Terminal, TPromptKind Kind, UnicodeString Name, UnicodeString Instructions,
  1143. TStrings * Prompts, TStrings * Results, bool & Result, void * /*Arg*/)
  1144. {
  1145. if (((Kind == pkPrompt) || (Kind == pkFileName)) && (FAuthenticateForm == NULL) &&
  1146. (Terminal->Status != ssOpening))
  1147. {
  1148. DebugAssert(Instructions.IsEmpty());
  1149. DebugAssert(Prompts->Count == 1);
  1150. DebugAssert(FLAGSET(int(Prompts->Objects[0]), pupEcho));
  1151. UnicodeString AResult = Results->Strings[0];
  1152. TInputDialogInitialize InputDialogInitialize = NULL;
  1153. if ((Kind == pkFileName) && !WinConfiguration->RenameWholeName)
  1154. {
  1155. InputDialogInitialize = FileNameInputDialogInitializeRenameBaseName;
  1156. }
  1157. Result = InputDialog(Name, Prompts->Strings[0], AResult, L"", NULL, false, InputDialogInitialize);
  1158. if (Result)
  1159. {
  1160. Results->Strings[0] = AResult;
  1161. }
  1162. }
  1163. else
  1164. {
  1165. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  1166. if (AuthenticateForm == NULL)
  1167. {
  1168. AuthenticateForm = MakeAuthenticateForm(Terminal);
  1169. }
  1170. try
  1171. {
  1172. Result = AuthenticateForm->PromptUser(Kind, Name, Instructions, Prompts, Results,
  1173. (FAuthenticateForm != NULL), Terminal->StoredCredentialsTried);
  1174. }
  1175. __finally
  1176. {
  1177. if (FAuthenticateForm == NULL)
  1178. {
  1179. delete AuthenticateForm;
  1180. }
  1181. }
  1182. }
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. void __fastcall TTerminalManager::TerminalDisplayBanner(
  1186. TTerminal * Terminal, UnicodeString SessionName,
  1187. const UnicodeString & Banner, bool & NeverShowAgain, int Options, unsigned int & Params)
  1188. {
  1189. DebugAssert(FAuthenticateForm != NULL);
  1190. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  1191. if (AuthenticateForm == NULL)
  1192. {
  1193. AuthenticateForm = MakeAuthenticateForm(Terminal);
  1194. }
  1195. try
  1196. {
  1197. AuthenticateForm->Banner(Banner, NeverShowAgain, Options, Params);
  1198. }
  1199. __finally
  1200. {
  1201. if (FAuthenticateForm == NULL)
  1202. {
  1203. delete AuthenticateForm;
  1204. }
  1205. }
  1206. }
  1207. //---------------------------------------------------------------------------
  1208. void __fastcall TTerminalManager::TerminalShowExtendedException(
  1209. TTerminal * Terminal, Exception * E, void * /*Arg*/)
  1210. {
  1211. if (ScpExplorer)
  1212. {
  1213. ScpExplorer->ShowExtendedException(Terminal, E);
  1214. }
  1215. else
  1216. {
  1217. ShowExtendedExceptionEx(Terminal, E);
  1218. }
  1219. }
  1220. //---------------------------------------------------------------------------
  1221. static TDateTime DirectoryReadingProgressDelay(0, 0, 1, 500);
  1222. //---------------------------------------------------------------------------
  1223. void __fastcall TTerminalManager::TerminalReadDirectoryProgress(
  1224. TObject * /*Sender*/, int Progress, int ResolvedLinks, bool & Cancel)
  1225. {
  1226. if (Progress == 0)
  1227. {
  1228. if (ScpExplorer != NULL)
  1229. {
  1230. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  1231. ScpExplorer->LockWindow();
  1232. }
  1233. FDirectoryReadingStart = Now();
  1234. if (!FProgressTitle.IsEmpty() || !FForegroundProgressTitle.IsEmpty())
  1235. {
  1236. FProgressTitle = L"";
  1237. FForegroundProgressTitle = L"";
  1238. UpdateAppTitle();
  1239. }
  1240. // Reset "was ESC ever pressed?" state
  1241. GetAsyncKeyState(VK_ESCAPE);
  1242. }
  1243. else if (Progress < 0)
  1244. {
  1245. if (Progress == -2)
  1246. {
  1247. // cancelled
  1248. if (ScpExplorer != NULL)
  1249. {
  1250. ScpExplorer->ReadDirectoryCancelled();
  1251. }
  1252. }
  1253. else
  1254. {
  1255. if (ScpExplorer != NULL)
  1256. {
  1257. ScpExplorer->UnlockWindow();
  1258. }
  1259. FProgressTitle = L"";
  1260. FForegroundProgressTitle = L"";
  1261. UpdateAppTitle();
  1262. }
  1263. }
  1264. else
  1265. {
  1266. // If the least significant bit is set,
  1267. // the key was pressed after the previous call to GetAsyncKeyState.
  1268. int KeyState = GetAsyncKeyState(VK_ESCAPE);
  1269. if (FLAGSET(KeyState, 0x01))
  1270. {
  1271. Cancel = true;
  1272. }
  1273. if ((Now() - FDirectoryReadingStart) >= DirectoryReadingProgressDelay)
  1274. {
  1275. // 4 is arbitrary number
  1276. FForegroundProgressTitle =
  1277. FMTLOAD(ResolvedLinks >= 4 ? DIRECTORY_READING_AND_RESOLVING_PROGRESS : DIRECTORY_READING_PROGRESS,
  1278. (Progress));
  1279. UpdateAppTitle();
  1280. }
  1281. }
  1282. }
  1283. //---------------------------------------------------------------------------
  1284. void __fastcall TTerminalManager::TerminalCustomCommand(
  1285. TTerminal * /*Terminal*/, const UnicodeString & Command, bool & Handled)
  1286. {
  1287. // Implementation has to be thread-safe
  1288. Handled = CopyCommandToClipboard(Command);
  1289. }
  1290. //---------------------------------------------------------------------------
  1291. void __fastcall TTerminalManager::AuthenticatingDone()
  1292. {
  1293. FAuthenticating--;
  1294. if (FAuthenticating == 0)
  1295. {
  1296. BusyEnd(FBusyToken);
  1297. FBusyToken = NULL;
  1298. }
  1299. if (!FKeepAuthenticateForm)
  1300. {
  1301. CloseAutheticateForm();
  1302. }
  1303. }
  1304. //---------------------------------------------------------------------------
  1305. void __fastcall TTerminalManager::TerminalInformation(
  1306. TTerminal * Terminal, const UnicodeString & Str, bool DebugUsedArg(Status), int Phase, const UnicodeString & Additional)
  1307. {
  1308. if (ScpExplorer != NULL)
  1309. {
  1310. ScpExplorer->TerminalConnecting();
  1311. }
  1312. if (Phase == 1)
  1313. {
  1314. if (FAuthenticating == 0)
  1315. {
  1316. FBusyToken = BusyStart();
  1317. }
  1318. FAuthenticating++;
  1319. }
  1320. else if (Phase == 0)
  1321. {
  1322. DebugAssert(FAuthenticating > 0);
  1323. AuthenticatingDone();
  1324. }
  1325. else
  1326. {
  1327. if (FAuthenticating > 0)
  1328. {
  1329. bool ShowPending = false;
  1330. if (FAuthenticateForm == NULL)
  1331. {
  1332. FAuthenticateForm = MakeAuthenticateForm(Terminal);
  1333. ShowPending = true;
  1334. }
  1335. FAuthenticateForm->Log(Str, Additional);
  1336. if (ShowPending)
  1337. {
  1338. FAuthenticateForm->ShowAsModal();
  1339. }
  1340. }
  1341. }
  1342. }
  1343. //---------------------------------------------------------------------------
  1344. void __fastcall TTerminalManager::OperationFinished(::TFileOperation Operation,
  1345. TOperationSide Side, bool Temp, const UnicodeString & FileName, bool Success,
  1346. TOnceDoneOperation & OnceDoneOperation)
  1347. {
  1348. DebugAssert(ScpExplorer);
  1349. ScpExplorer->OperationFinished(Operation, Side, Temp, FileName, Success,
  1350. OnceDoneOperation);
  1351. }
  1352. //---------------------------------------------------------------------------
  1353. void __fastcall TTerminalManager::OperationProgress(
  1354. TFileOperationProgressType & ProgressData)
  1355. {
  1356. UpdateAppTitle();
  1357. DebugAssert(ScpExplorer);
  1358. ScpExplorer->OperationProgress(ProgressData);
  1359. }
  1360. //---------------------------------------------------------------------------
  1361. void __fastcall TTerminalManager::QueueEvent(TTerminalQueue * Queue, TQueueEvent Event)
  1362. {
  1363. TGuard Guard(FQueueSection);
  1364. FQueueEvents.push_back(std::make_pair(Queue, Event));
  1365. }
  1366. //---------------------------------------------------------------------------
  1367. void __fastcall TTerminalManager::DoConfigurationChange()
  1368. {
  1369. DebugAssert(Configuration);
  1370. DebugAssert(Configuration == WinConfiguration);
  1371. TTerminalQueue * Queue;
  1372. for (int Index = 0; Index < Count; Index++)
  1373. {
  1374. DebugAssert(Sessions[Index]->Log);
  1375. Sessions[Index]->Log->ReflectSettings();
  1376. Sessions[Index]->ActionLog->ReflectSettings();
  1377. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1378. SetQueueConfiguration(Queue);
  1379. }
  1380. if (ScpExplorer)
  1381. {
  1382. ScpExplorer->ConfigurationChanged();
  1383. }
  1384. }
  1385. //---------------------------------------------------------------------------
  1386. void __fastcall TTerminalManager::ConfigurationChange(TObject * /*Sender*/)
  1387. {
  1388. if (FMainThread == GetCurrentThreadId())
  1389. {
  1390. DoConfigurationChange();
  1391. }
  1392. else
  1393. {
  1394. TGuard Guard(FChangeSection.get());
  1395. FPendingConfigurationChange++;
  1396. }
  1397. }
  1398. //---------------------------------------------------------------------------
  1399. void __fastcall TTerminalManager::SessionReady()
  1400. {
  1401. UpdateScpExplorer();
  1402. ScpExplorer->SessionReady();
  1403. }
  1404. //---------------------------------------------------------------------------
  1405. TStrings * __fastcall TTerminalManager::GetSessionList()
  1406. {
  1407. FSessionList->Clear();
  1408. for (int i = 0; i < Count; i++)
  1409. {
  1410. TManagedTerminal * Terminal = Sessions[i];
  1411. UnicodeString Name = GetSessionTitle(Terminal, true);
  1412. FSessionList->AddObject(Name, Terminal);
  1413. }
  1414. return FSessionList;
  1415. }
  1416. //---------------------------------------------------------------------------
  1417. int __fastcall TTerminalManager::GetActiveSessionIndex()
  1418. {
  1419. return (ActiveSession != NULL) ? IndexOf(ActiveSession) : -1;
  1420. }
  1421. //---------------------------------------------------------------------------
  1422. void __fastcall TTerminalManager::SetActiveSessionIndex(int value)
  1423. {
  1424. ActiveSession = Sessions[value];
  1425. }
  1426. //---------------------------------------------------------------------------
  1427. UnicodeString TTerminalManager::GetPathForSessionTabName(const UnicodeString & Path)
  1428. {
  1429. UnicodeString Result = Path;
  1430. const int MaxPathLen = 16;
  1431. if ((WinConfiguration->SessionTabNameFormat == stnfShortPathTrunc) &&
  1432. (Result.Length() > MaxPathLen))
  1433. {
  1434. Result = Result.SubString(1, MaxPathLen - 2) + Ellipsis;
  1435. }
  1436. return Result;
  1437. }
  1438. //---------------------------------------------------------------------------
  1439. UnicodeString __fastcall TTerminalManager::GetSessionTitle(TManagedTerminal * Session, bool Unique)
  1440. {
  1441. UnicodeString Result;
  1442. if (!Session->LocalBrowser)
  1443. {
  1444. Result = Session->SessionData->SessionName;
  1445. if (Unique &&
  1446. (WinConfiguration->SessionTabNameFormat != stnfNone))
  1447. {
  1448. int Index = IndexOf(Session);
  1449. // not for background transfer sessions and disconnected sessions
  1450. if ((Index >= 0) && Session->Active)
  1451. {
  1452. for (int Index2 = 0; Index2 < Count; Index2++)
  1453. {
  1454. UnicodeString Name = Sessions[Index2]->SessionData->SessionName;
  1455. if ((Sessions[Index2] != Session) &&
  1456. Sessions[Index2]->Active &&
  1457. SameText(Name, Result))
  1458. {
  1459. UnicodeString Path = ExtractShortName(Session->CurrentDirectory, true);
  1460. if (!Path.IsEmpty())
  1461. {
  1462. Path = GetPathForSessionTabName(Path);
  1463. Result = FORMAT(L"%s (%s)", (Result, Path));
  1464. }
  1465. break;
  1466. }
  1467. }
  1468. }
  1469. }
  1470. }
  1471. else
  1472. {
  1473. // should happen only when closing
  1474. if (ScpExplorer != NULL)
  1475. {
  1476. Result = ScpExplorer->GetLocalBrowserSessionTitle(Session);
  1477. }
  1478. }
  1479. return Result;
  1480. }
  1481. //---------------------------------------------------------------------------
  1482. UnicodeString __fastcall TTerminalManager::GetActiveSessionAppTitle()
  1483. {
  1484. UnicodeString Result;
  1485. if ((ActiveSession != NULL) && !ActiveSession->LocalBrowser)
  1486. {
  1487. Result = GetSessionTitle(ActiveSession, false);
  1488. }
  1489. return Result;
  1490. }
  1491. //---------------------------------------------------------------------------
  1492. TTerminalQueue * __fastcall TTerminalManager::GetActiveQueue()
  1493. {
  1494. TTerminalQueue * Result = NULL;
  1495. if (ActiveSession != NULL)
  1496. {
  1497. Result = reinterpret_cast<TTerminalQueue *>(FQueues->Items[ActiveSessionIndex]);
  1498. }
  1499. return Result;
  1500. }
  1501. //---------------------------------------------------------------------------
  1502. void __fastcall TTerminalManager::CycleTerminals(bool Forward)
  1503. {
  1504. if (Count > 0)
  1505. {
  1506. int Index = ActiveSessionIndex;
  1507. Index += Forward ? 1 : -1;
  1508. if (Index < 0)
  1509. {
  1510. Index = Count-1;
  1511. }
  1512. else if (Index >= Count)
  1513. {
  1514. Index = 0;
  1515. }
  1516. ActiveSessionIndex = Index;
  1517. }
  1518. }
  1519. //---------------------------------------------------------------------------
  1520. bool __fastcall TTerminalManager::CanOpenInPutty()
  1521. {
  1522. return (ActiveTerminal != NULL) && !GUIConfiguration->PuttyPath.Trim().IsEmpty();
  1523. }
  1524. //---------------------------------------------------------------------------
  1525. void __fastcall TTerminalManager::OpenInPutty()
  1526. {
  1527. Configuration->Usage->Inc(L"OpenInPutty");
  1528. TSessionData * Data = NULL;
  1529. try
  1530. {
  1531. // Is NULL on the first session when called from ConnectActiveTerminal()
  1532. // due to WinConfiguration->AutoOpenInPutty
  1533. if (ScpExplorer != NULL)
  1534. {
  1535. Data = ScpExplorer->CloneCurrentSessionData();
  1536. }
  1537. else
  1538. {
  1539. Data = new TSessionData(L"");
  1540. DebugAssert(ActiveTerminal != NULL);
  1541. Data->Assign(ActiveTerminal->SessionData);
  1542. ActiveTerminal->UpdateSessionCredentials(Data);
  1543. }
  1544. if (ActiveTerminal->TunnelLocalPortNumber != 0)
  1545. {
  1546. Data->ConfigureTunnel(ActiveTerminal->TunnelLocalPortNumber);
  1547. }
  1548. OpenSessionInPutty(Data);
  1549. }
  1550. __finally
  1551. {
  1552. delete Data;
  1553. }
  1554. }
  1555. //---------------------------------------------------------------------------
  1556. void __fastcall TTerminalManager::NewSession(
  1557. const UnicodeString & SessionUrl, bool ReloadSessions, TForm * LinkedForm, bool ReplaceExisting)
  1558. {
  1559. if (ReloadSessions)
  1560. {
  1561. StoredSessions->Reload();
  1562. }
  1563. std::unique_ptr<TObjectList> DataList;
  1564. bool Retry;
  1565. do
  1566. {
  1567. Retry = false;
  1568. if (!DataList) // first round
  1569. {
  1570. DataList.reset(new TObjectList());
  1571. UnicodeString DownloadFile; // unused
  1572. GetLoginData(SessionUrl, NULL, DataList.get(), DownloadFile, true, LinkedForm);
  1573. }
  1574. else
  1575. {
  1576. if (!DoLoginDialog(DataList.get(), LinkedForm))
  1577. {
  1578. Abort(); // As GetLoginData would do
  1579. }
  1580. }
  1581. if (DataList->Count > 0)
  1582. {
  1583. if (ReplaceExisting)
  1584. {
  1585. // Tested for only the implicit Commanders' local browser
  1586. DebugAssert((Count == 0) || ((Count == 1) && Sessions[0]->LocalBrowser));
  1587. TAutoNestingCounter UpdatingCounter(FUpdating); // prevent tab flicker
  1588. FreeAll();
  1589. }
  1590. TManagedTerminal * ANewSession = NewSessions(DataList.get());
  1591. bool AdHoc = (DataList->Count == 1) && (StoredSessions->FindSame(reinterpret_cast<TSessionData *>(DataList->Items[0])) == NULL);
  1592. bool CanRetry = SessionUrl.IsEmpty() && AdHoc;
  1593. bool ShowLoginWhenNoSession = WinConfiguration->ShowLoginWhenNoSession;
  1594. if (CanRetry)
  1595. {
  1596. // we will show our own login dialog, so prevent opening an empty one
  1597. WinConfiguration->ShowLoginWhenNoSession = false;
  1598. }
  1599. try
  1600. {
  1601. ActiveSession = ANewSession;
  1602. }
  1603. __finally
  1604. {
  1605. if (CanRetry) // do not reset the value, unless really needed, as it can theoretically be changed meanwhile by the user
  1606. {
  1607. WinConfiguration->ShowLoginWhenNoSession = ShowLoginWhenNoSession;
  1608. }
  1609. }
  1610. Retry = CanRetry && (ActiveSession != ANewSession);
  1611. }
  1612. }
  1613. while (Retry);
  1614. }
  1615. //---------------------------------------------------------------------------
  1616. void __fastcall TTerminalManager::Idle(bool SkipCurrentTerminal)
  1617. {
  1618. if (FPendingConfigurationChange > 0) // optimization
  1619. {
  1620. bool Changed = false;
  1621. {
  1622. TGuard Guard(FChangeSection.get());
  1623. if (DebugAlwaysTrue(FPendingConfigurationChange > 0))
  1624. {
  1625. FPendingConfigurationChange--;
  1626. Changed = true;
  1627. }
  1628. }
  1629. if (Changed)
  1630. {
  1631. DoConfigurationChange();
  1632. }
  1633. }
  1634. for (int Index = 0; Index < Count; Index++)
  1635. {
  1636. TManagedTerminal * Terminal = Sessions[Index];
  1637. try
  1638. {
  1639. if (!SkipCurrentTerminal || (Terminal != ActiveTerminal))
  1640. {
  1641. // make sure Idle is called on the thread that runs the terminal
  1642. if (Terminal->TerminalThread != NULL)
  1643. {
  1644. Terminal->TerminalThread->Idle();
  1645. }
  1646. else
  1647. {
  1648. if (Terminal->Active)
  1649. {
  1650. Terminal->Idle();
  1651. }
  1652. }
  1653. if (Terminal->Active)
  1654. {
  1655. DebugAssert(Index < FQueues->Count);
  1656. if (Index < FQueues->Count)
  1657. {
  1658. reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index])->Idle();
  1659. }
  1660. }
  1661. }
  1662. }
  1663. catch(Exception & E)
  1664. {
  1665. if (Terminal == ActiveTerminal)
  1666. {
  1667. // throw further, so that the exception is handled in proper place
  1668. // (particularly in broken-transfer reconnect handler, bug 72)
  1669. throw;
  1670. }
  1671. else
  1672. {
  1673. // we may not have inactive terminal, unless there is a explorer,
  1674. // also Idle is called from explorer anyway
  1675. DebugAssert(ScpExplorer != NULL);
  1676. if (ScpExplorer != NULL)
  1677. {
  1678. ScpExplorer->InactiveTerminalException(Terminal, &E);
  1679. }
  1680. if (!Terminal->Active)
  1681. {
  1682. // if session is lost, save the error message and rethrow it
  1683. // once the terminal gets activated
  1684. FTerminationMessages->Strings[Index] = E.Message;
  1685. }
  1686. }
  1687. }
  1688. }
  1689. TTerminalQueue * QueueWithEvent;
  1690. TQueueEvent QueueEvent;
  1691. do
  1692. {
  1693. QueueWithEvent = NULL;
  1694. {
  1695. TGuard Guard(FQueueSection);
  1696. if (!FQueueEvents.empty())
  1697. {
  1698. QueueWithEvent = FQueueEvents[0].first;
  1699. QueueEvent = FQueueEvents[0].second;
  1700. FQueueEvents.erase(FQueueEvents.begin());
  1701. }
  1702. }
  1703. if (QueueWithEvent != NULL)
  1704. {
  1705. int Index = FQueues->IndexOf(QueueWithEvent);
  1706. // the session may not exist anymore
  1707. if (Index >= 0)
  1708. {
  1709. TManagedTerminal * Terminal = Sessions[Index];
  1710. // we can hardly have a queue event without explorer
  1711. DebugAssert(ScpExplorer != NULL);
  1712. if (ScpExplorer != NULL)
  1713. {
  1714. ScpExplorer->QueueEvent(Terminal, QueueWithEvent, QueueEvent);
  1715. }
  1716. }
  1717. }
  1718. }
  1719. while (QueueWithEvent != NULL);
  1720. }
  1721. //---------------------------------------------------------------------------
  1722. void __fastcall TTerminalManager::MasterPasswordPrompt()
  1723. {
  1724. if (GetCurrentThreadId() == MainThreadID)
  1725. {
  1726. if (!DoMasterPasswordDialog())
  1727. {
  1728. Abort();
  1729. }
  1730. }
  1731. else
  1732. {
  1733. // this can happen only when we keep cancelling all master password prompts
  1734. // as long as the sessing finally connects (session password has to be
  1735. // explictly typed in), and background transfer is started
  1736. Abort();
  1737. }
  1738. }
  1739. //---------------------------------------------------------------------------
  1740. void __fastcall TTerminalManager::Move(TTerminal * Source, TTerminal * Target)
  1741. {
  1742. int SourceIndex = IndexOf(Source);
  1743. int TargetIndex = IndexOf(Target);
  1744. TTerminalList::Move(SourceIndex, TargetIndex);
  1745. FQueues->Move(SourceIndex, TargetIndex);
  1746. DoSessionListChanged();
  1747. // when there are indexed sessions with the same name,
  1748. // the index may change when reordering the sessions
  1749. UpdateAppTitle();
  1750. }
  1751. //---------------------------------------------------------------------------
  1752. void __fastcall TTerminalManager::DoSessionListChanged()
  1753. {
  1754. if ((FScpExplorer != NULL) && !Updating)
  1755. {
  1756. FScpExplorer->SessionListChanged();
  1757. }
  1758. }
  1759. //---------------------------------------------------------------------------
  1760. void __fastcall TTerminalManager::SaveWorkspace(TList * DataList)
  1761. {
  1762. for (int Index = 0; Index < Count; Index++)
  1763. {
  1764. TManagedTerminal * ManagedTerminal = Sessions[Index];
  1765. TSessionData * Data = StoredSessions->SaveWorkspaceData(ManagedTerminal->StateData, Index);
  1766. if (ManagedTerminal->Active)
  1767. {
  1768. ManagedTerminal->UpdateSessionCredentials(Data);
  1769. }
  1770. DataList->Add(Data);
  1771. }
  1772. }
  1773. //---------------------------------------------------------------------------
  1774. bool __fastcall TTerminalManager::IsActiveTerminalForSite(TTerminal * Terminal, TSessionData * Data)
  1775. {
  1776. bool Result = Terminal->Active;
  1777. if (Result)
  1778. {
  1779. std::unique_ptr<TSessionData> TerminalData(Terminal->SessionData->Clone());
  1780. Terminal->UpdateSessionCredentials(TerminalData.get());
  1781. Result = TerminalData->IsSameSite(Data);
  1782. }
  1783. return Result;
  1784. }
  1785. //---------------------------------------------------------------------------
  1786. TManagedTerminal * __fastcall TTerminalManager::FindActiveTerminalForSite(TSessionData * Data)
  1787. {
  1788. TManagedTerminal * Result = NULL;
  1789. for (int Index = 0; (Result == NULL) && (Index < Count); Index++)
  1790. {
  1791. TManagedTerminal * Terminal = Sessions[Index];
  1792. if (IsActiveTerminalForSite(Terminal, Data))
  1793. {
  1794. Result = Terminal;
  1795. }
  1796. }
  1797. return Result;
  1798. }
  1799. //---------------------------------------------------------------------------
  1800. TTerminalQueue * __fastcall TTerminalManager::FindQueueForTerminal(TTerminal * Terminal)
  1801. {
  1802. int Index = IndexOf(Terminal);
  1803. return reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1804. }
  1805. //---------------------------------------------------------------------------
  1806. bool __fastcall TTerminalManager::UploadPublicKey(
  1807. TTerminal * Terminal, TSessionData * Data, UnicodeString & FileName)
  1808. {
  1809. std::unique_ptr<TOpenDialog> OpenDialog(new TOpenDialog(Application));
  1810. OpenDialog->Title = LoadStr(LOGIN_PUBLIC_KEY_TITLE);
  1811. OpenDialog->Filter = LoadStr(LOGIN_PUBLIC_KEY_FILTER);
  1812. OpenDialog->DefaultExt = PuttyKeyExt;
  1813. OpenDialog->FileName = FileName;
  1814. bool Result = OpenDialog->Execute();
  1815. if (Result)
  1816. {
  1817. Configuration->Usage->Inc(L"PublicKeyInstallation");
  1818. FileName = OpenDialog->FileName;
  1819. VerifyAndConvertKey(FileName, false);
  1820. bool AdHocTerminal = (Terminal == NULL);
  1821. std::unique_ptr<TTerminal> TerminalOwner;
  1822. if (AdHocTerminal)
  1823. {
  1824. DebugAssert(Data != NULL);
  1825. TAutoFlag KeepAuthenticateFormFlag(FKeepAuthenticateForm);
  1826. try
  1827. {
  1828. TerminalOwner.reset(CreateTerminal(Data));
  1829. Terminal = TerminalOwner.get();
  1830. SetupTerminal(Terminal);
  1831. Terminal->OnProgress = NULL;
  1832. Terminal->OnFinished = NULL;
  1833. DoConnectTerminal(Terminal, false, true);
  1834. }
  1835. catch (Exception & E)
  1836. {
  1837. CloseAutheticateForm();
  1838. throw;
  1839. }
  1840. }
  1841. UnicodeString Installed;
  1842. try
  1843. {
  1844. UnicodeString SshImplementation = Terminal->GetSessionInfo().SshImplementation;
  1845. UnicodeString NotOpenSSHMessage = FMTLOAD(LOGIN_NOT_OPENSSH, (SshImplementation));
  1846. if (IsOpenSSH(SshImplementation) ||
  1847. (MessageDialog(NotOpenSSHMessage, qtConfirmation, qaOK | qaCancel, HELP_LOGIN_AUTHORIZED_KEYS) == qaOK))
  1848. {
  1849. // Ad-hoc terminal
  1850. if (FAuthenticateForm != NULL)
  1851. {
  1852. UnicodeString Comment;
  1853. bool UnusedHasCertificate;
  1854. GetPublicKeyLine(FileName, Comment, UnusedHasCertificate);
  1855. FAuthenticateForm->Log(FMTLOAD(LOGIN_PUBLIC_KEY_UPLOAD, (Comment)));
  1856. }
  1857. Installed = Terminal->UploadPublicKey(FileName);
  1858. }
  1859. }
  1860. __finally
  1861. {
  1862. CloseAutheticateForm(); // When uploading from Login dialog
  1863. }
  1864. if (!Installed.IsEmpty())
  1865. {
  1866. Terminal->LogEvent(L"Public key installation done.");
  1867. if (AdHocTerminal)
  1868. {
  1869. TerminalOwner.reset(NULL);
  1870. }
  1871. else
  1872. {
  1873. Terminal->Log->AddSeparator();
  1874. }
  1875. MessageDialog(Installed, qtInformation, qaOK, HELP_LOGIN_AUTHORIZED_KEYS);
  1876. }
  1877. }
  1878. return Result;
  1879. }
  1880. //---------------------------------------------------------------------------
  1881. bool TTerminalManager::IsUpdating()
  1882. {
  1883. return (FUpdating > 0);
  1884. }
  1885. //---------------------------------------------------------------------------
  1886. bool TTerminalManager::HookFatalExceptionMessageDialog(TMessageParams & Params)
  1887. {
  1888. bool Result =
  1889. DebugAlwaysTrue(ActiveTerminal != NULL) &&
  1890. DebugAlwaysTrue(Params.Timer == 0) &&
  1891. DebugAlwaysTrue(Params.TimerEvent == NULL) &&
  1892. DebugAlwaysTrue(FTerminalWithFatalExceptionTimer == NULL);
  1893. if (Result)
  1894. {
  1895. Params.Timer = MSecsPerSec / 4;
  1896. Params.TimerEvent = TerminalFatalExceptionTimer;
  1897. FTerminalWithFatalExceptionTimer = ActiveTerminal;
  1898. FTerminalReconnnecteScheduled = false;
  1899. }
  1900. return Result;
  1901. }
  1902. //---------------------------------------------------------------------------
  1903. void TTerminalManager::UnhookFatalExceptionMessageDialog()
  1904. {
  1905. DebugAssert(FTerminalWithFatalExceptionTimer != NULL);
  1906. FTerminalWithFatalExceptionTimer = NULL;
  1907. }
  1908. //---------------------------------------------------------------------------
  1909. bool TTerminalManager::ScheduleTerminalReconnnect(TTerminal * Terminal)
  1910. {
  1911. bool Result = (FTerminalWithFatalExceptionTimer == Terminal);
  1912. if (Result)
  1913. {
  1914. FTerminalReconnnecteScheduled = true;
  1915. }
  1916. return Result;
  1917. }
  1918. //---------------------------------------------------------------------------
  1919. void __fastcall TTerminalManager::TerminalFatalExceptionTimer(unsigned int & Result)
  1920. {
  1921. if (FTerminalReconnnecteScheduled)
  1922. {
  1923. Result = qaRetry;
  1924. FTerminalReconnnecteScheduled = false;
  1925. }
  1926. }