TerminalManager.cpp 61 KB

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