TerminalManager.cpp 73 KB

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