TerminalManager.cpp 58 KB

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