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