TerminalManager.cpp 62 KB

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