TerminalManager.cpp 64 KB

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