TerminalManager.cpp 80 KB

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