1
0

TerminalManager.cpp 64 KB

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