TerminalManager.cpp 61 KB

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