TerminalManager.cpp 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476
  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. // See also VCL's TTaskbar class
  1176. FTaskbarButtonCreatedMessage = RegisterWindowMessage(L"TaskbarButtonCreated");
  1177. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  1178. ChangeWindowMessageFilterExProc ChangeWindowMessageFilterEx =
  1179. (ChangeWindowMessageFilterExProc)GetProcAddress(User32Library, "ChangeWindowMessageFilterEx");
  1180. if (ChangeWindowMessageFilterEx != NULL)
  1181. {
  1182. // without this we won't get TaskbarButtonCreated, when app is running elevated
  1183. ChangeWindowMessageFilterEx(
  1184. Application->Handle, FTaskbarButtonCreatedMessage, MSGFLT_ALLOW, NULL);
  1185. }
  1186. }
  1187. //---------------------------------------------------------------------------
  1188. void __fastcall TTerminalManager::CreateTaskbarList()
  1189. {
  1190. ReleaseTaskbarList();
  1191. if(SUCCEEDED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL,
  1192. IID_ITaskbarList3, (void **) &FTaskbarList)))
  1193. {
  1194. if (ScpExplorer != NULL)
  1195. {
  1196. UpdateTaskbarList();
  1197. }
  1198. }
  1199. }
  1200. //---------------------------------------------------------------------------
  1201. void __fastcall TTerminalManager::ReleaseTaskbarList()
  1202. {
  1203. if (FTaskbarList != NULL)
  1204. {
  1205. FTaskbarList->Release();
  1206. }
  1207. }
  1208. //---------------------------------------------------------------------------
  1209. void __fastcall TTerminalManager::UpdateTaskbarList()
  1210. {
  1211. ScpExplorer->UpdateTaskbarList(FTaskbarList);
  1212. }
  1213. //---------------------------------------------------------------------------
  1214. void __fastcall TTerminalManager::DeleteLocalFile(const UnicodeString FileName, bool Alternative, int & Deleted)
  1215. {
  1216. Deleted = RecursiveDeleteFileChecked(FileName, (WinConfiguration->DeleteToRecycleBin != Alternative));
  1217. }
  1218. //---------------------------------------------------------------------------
  1219. void __fastcall TTerminalManager::TerminalQueryUser(TObject * Sender,
  1220. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  1221. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * /*Arg*/)
  1222. {
  1223. TTerminal * Terminal = DebugNotNull(dynamic_cast<TTerminal *>(Sender));
  1224. UnicodeString HelpKeyword;
  1225. TMessageParams MessageParams(Params);
  1226. UnicodeString AQuery = Query;
  1227. if (Params != NULL)
  1228. {
  1229. HelpKeyword = Params->HelpKeyword;
  1230. if (FLAGSET(Params->Params, qpFatalAbort))
  1231. {
  1232. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  1233. if (!MessageParams.TimerMessage.IsEmpty())
  1234. {
  1235. MessageParams.TimerMessage = FMTLOAD(WARN_FATAL_ERROR, (MessageParams.TimerMessage));
  1236. }
  1237. }
  1238. }
  1239. if (ScpExplorer)
  1240. {
  1241. Answer = ScpExplorer->MoreMessageDialog(AQuery, MoreMessages, Type, Answers,
  1242. HelpKeyword, &MessageParams, Terminal);
  1243. }
  1244. else
  1245. {
  1246. Answer = MoreMessageDialog(AQuery, MoreMessages, Type, Answers, HelpKeyword,
  1247. &MessageParams);
  1248. }
  1249. }
  1250. //---------------------------------------------------------------------------
  1251. void __fastcall TTerminalManager::AuthenticateFormCancel(TObject * Sender)
  1252. {
  1253. TAuthenticateForm * Form = dynamic_cast<TAuthenticateForm *>(Sender);
  1254. DebugAssert(Form != NULL);
  1255. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Form->Terminal);
  1256. // will be null e.g. for background transfers
  1257. if (ManagedTerminal != NULL)
  1258. {
  1259. TTerminalThread * TerminalThread = ManagedTerminal->TerminalThread;
  1260. // can be NULL for reconnects from transfers
  1261. if ((TerminalThread != NULL) && !TerminalThread->Cancelling)
  1262. {
  1263. Form->Log(LoadStr(AUTH_CANCELLING));
  1264. TerminalThread->Cancel();
  1265. }
  1266. }
  1267. FAuthenticationCancelled = true;
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. TAuthenticateForm * __fastcall TTerminalManager::MakeAuthenticateForm(
  1271. TTerminal * Terminal)
  1272. {
  1273. TAuthenticateForm * Dialog = SafeFormCreate<TAuthenticateForm>();
  1274. Dialog->Init(Terminal);
  1275. DebugAssert(Dialog->OnCancel == NULL);
  1276. Dialog->OnCancel = AuthenticateFormCancel;
  1277. return Dialog;
  1278. }
  1279. //---------------------------------------------------------------------------
  1280. void __fastcall TTerminalManager::FileNameInputDialogInitializeRenameBaseName(
  1281. TObject * /*Sender*/, TInputDialogData * Data)
  1282. {
  1283. EditSelectBaseName(Data->Edit->Handle);
  1284. }
  1285. //---------------------------------------------------------------------------
  1286. void __fastcall TTerminalManager::TerminalPromptUser(
  1287. TTerminal * Terminal, TPromptKind Kind, UnicodeString Name, UnicodeString Instructions,
  1288. TStrings * Prompts, TStrings * Results, bool & Result, void * /*Arg*/)
  1289. {
  1290. if (((Kind == pkPrompt) || (Kind == pkFileName)) && (FAuthenticateForm == NULL) &&
  1291. (Terminal->Status != ssOpening))
  1292. {
  1293. DebugAssert(Instructions.IsEmpty());
  1294. DebugAssert(Prompts->Count == 1);
  1295. DebugAssert(FLAGSET(int(Prompts->Objects[0]), pupEcho));
  1296. UnicodeString AResult = Results->Strings[0];
  1297. TInputDialogInitialize InputDialogInitialize = NULL;
  1298. if ((Kind == pkFileName) && !WinConfiguration->RenameWholeName)
  1299. {
  1300. InputDialogInitialize = FileNameInputDialogInitializeRenameBaseName;
  1301. }
  1302. Result = InputDialog(Name, Prompts->Strings[0], AResult, L"", NULL, false, InputDialogInitialize);
  1303. if (Result)
  1304. {
  1305. Results->Strings[0] = AResult;
  1306. }
  1307. }
  1308. else
  1309. {
  1310. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  1311. if (AuthenticateForm == NULL)
  1312. {
  1313. AuthenticateForm = MakeAuthenticateForm(Terminal);
  1314. }
  1315. try
  1316. {
  1317. Result = AuthenticateForm->PromptUser(Kind, Name, Instructions, Prompts, Results,
  1318. (FAuthenticateForm != NULL), Terminal->StoredCredentialsTried);
  1319. }
  1320. __finally
  1321. {
  1322. if (FAuthenticateForm == NULL)
  1323. {
  1324. delete AuthenticateForm;
  1325. }
  1326. }
  1327. }
  1328. }
  1329. //---------------------------------------------------------------------------
  1330. void __fastcall TTerminalManager::TerminalDisplayBanner(
  1331. TTerminal * Terminal, UnicodeString DebugUsedArg(SessionName),
  1332. const UnicodeString & Banner, bool & NeverShowAgain, int Options, unsigned int & Params)
  1333. {
  1334. DebugAssert(FAuthenticateForm != NULL);
  1335. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  1336. if (AuthenticateForm == NULL)
  1337. {
  1338. AuthenticateForm = MakeAuthenticateForm(Terminal);
  1339. }
  1340. try
  1341. {
  1342. AuthenticateForm->Banner(Banner, NeverShowAgain, Options, Params);
  1343. }
  1344. __finally
  1345. {
  1346. if (FAuthenticateForm == NULL)
  1347. {
  1348. delete AuthenticateForm;
  1349. }
  1350. }
  1351. }
  1352. //---------------------------------------------------------------------------
  1353. void __fastcall TTerminalManager::TerminalShowExtendedException(
  1354. TTerminal * Terminal, Exception * E, void * /*Arg*/)
  1355. {
  1356. if (ScpExplorer)
  1357. {
  1358. ScpExplorer->ShowExtendedException(Terminal, E);
  1359. }
  1360. else
  1361. {
  1362. ShowExtendedExceptionEx(Terminal, E);
  1363. }
  1364. }
  1365. //---------------------------------------------------------------------------
  1366. static TDateTime DirectoryReadingProgressDelay(0, 0, 1, 500);
  1367. //---------------------------------------------------------------------------
  1368. void __fastcall TTerminalManager::TerminalReadDirectoryProgress(
  1369. TObject * Sender, int Progress, int ResolvedLinks, bool & Cancel)
  1370. {
  1371. DebugAssert((Sender == FOpeningTerminal) == (FAuthenticateForm != NULL));
  1372. if (Progress == 0)
  1373. {
  1374. if ((ScpExplorer != NULL) && (Sender != FOpeningTerminal))
  1375. {
  1376. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  1377. ScpExplorer->LockWindow();
  1378. }
  1379. FDirectoryReadingStart = Now();
  1380. if (!FProgressTitle.IsEmpty() || !FForegroundProgressTitle.IsEmpty())
  1381. {
  1382. FProgressTitle = L"";
  1383. FForegroundProgressTitle = L"";
  1384. UpdateAppTitle();
  1385. }
  1386. // Reset "was ESC ever pressed?" state
  1387. GetAsyncKeyState(VK_ESCAPE);
  1388. }
  1389. else if (Progress < 0)
  1390. {
  1391. if (Progress == -2)
  1392. {
  1393. // cancelled
  1394. if (ScpExplorer != NULL)
  1395. {
  1396. ScpExplorer->ReadDirectoryCancelled();
  1397. }
  1398. }
  1399. else
  1400. {
  1401. if ((ScpExplorer != NULL) && (Sender != FOpeningTerminal))
  1402. {
  1403. ScpExplorer->UnlockWindow();
  1404. }
  1405. FProgressTitle = L"";
  1406. FForegroundProgressTitle = L"";
  1407. UpdateAppTitle();
  1408. }
  1409. }
  1410. else
  1411. {
  1412. // If the least significant bit is set,
  1413. // the key was pressed after the previous call to GetAsyncKeyState.
  1414. int KeyState = GetAsyncKeyState(VK_ESCAPE);
  1415. if (FLAGSET(KeyState, 0x01))
  1416. {
  1417. Cancel = true;
  1418. }
  1419. if ((Now() - FDirectoryReadingStart) >= DirectoryReadingProgressDelay)
  1420. {
  1421. // 4 is arbitrary number
  1422. FForegroundProgressTitle =
  1423. FMTLOAD(ResolvedLinks >= 4 ? DIRECTORY_READING_AND_RESOLVING_PROGRESS : DIRECTORY_READING_PROGRESS,
  1424. (Progress));
  1425. UpdateAppTitle();
  1426. }
  1427. }
  1428. }
  1429. //---------------------------------------------------------------------------
  1430. void __fastcall TTerminalManager::TerminalCustomCommand(
  1431. TTerminal * /*Terminal*/, const UnicodeString & Command, bool & Handled)
  1432. {
  1433. // Implementation has to be thread-safe
  1434. Handled = CopyCommandToClipboard(Command);
  1435. }
  1436. //---------------------------------------------------------------------------
  1437. void __fastcall TTerminalManager::AuthenticatingDone()
  1438. {
  1439. FAuthenticating--;
  1440. if (FAuthenticating == 0)
  1441. {
  1442. BusyEnd(FBusyToken);
  1443. FBusyToken = NULL;
  1444. }
  1445. if (!FKeepAuthenticateForm)
  1446. {
  1447. CloseAutheticateForm();
  1448. }
  1449. }
  1450. //---------------------------------------------------------------------------
  1451. void __fastcall TTerminalManager::TerminalInformation(
  1452. TTerminal * Terminal, const UnicodeString & Str, int Phase, const UnicodeString & Additional)
  1453. {
  1454. if (ScpExplorer != NULL)
  1455. {
  1456. ScpExplorer->TerminalConnecting();
  1457. }
  1458. if (Phase == 1)
  1459. {
  1460. if (FAuthenticating == 0)
  1461. {
  1462. FBusyToken = BusyStart();
  1463. }
  1464. FAuthenticating++;
  1465. }
  1466. else if (Phase == 0)
  1467. {
  1468. DebugAssert(FAuthenticating > 0);
  1469. AuthenticatingDone();
  1470. }
  1471. else
  1472. {
  1473. if (FAuthenticating > 0)
  1474. {
  1475. bool ShowPending = false;
  1476. if (FAuthenticateForm == NULL)
  1477. {
  1478. FAuthenticateForm = MakeAuthenticateForm(Terminal);
  1479. ShowPending = true;
  1480. }
  1481. FAuthenticateForm->Log(Str, Additional);
  1482. if (ShowPending)
  1483. {
  1484. FAuthenticateForm->ShowAsModal();
  1485. }
  1486. }
  1487. }
  1488. }
  1489. //---------------------------------------------------------------------------
  1490. void __fastcall TTerminalManager::OperationFinished(::TFileOperation Operation,
  1491. TOperationSide Side, bool Temp, const UnicodeString & FileName, bool Success, bool NotCancelled,
  1492. TOnceDoneOperation & OnceDoneOperation)
  1493. {
  1494. DebugAssert(ScpExplorer);
  1495. ScpExplorer->OperationFinished(Operation, Side, Temp, FileName, Success, NotCancelled, OnceDoneOperation);
  1496. }
  1497. //---------------------------------------------------------------------------
  1498. void __fastcall TTerminalManager::OperationProgress(
  1499. TFileOperationProgressType & ProgressData)
  1500. {
  1501. UpdateAppTitle();
  1502. DebugAssert(ScpExplorer);
  1503. ScpExplorer->OperationProgress(ProgressData);
  1504. }
  1505. //---------------------------------------------------------------------------
  1506. void __fastcall TTerminalManager::QueueEvent(TTerminalQueue * Queue, TQueueEvent Event)
  1507. {
  1508. TGuard Guard(FQueueSection);
  1509. FQueueEvents.push_back(std::make_pair(Queue, Event));
  1510. }
  1511. //---------------------------------------------------------------------------
  1512. void __fastcall TTerminalManager::DoConfigurationChange()
  1513. {
  1514. DebugAssert(Configuration);
  1515. DebugAssert(Configuration == WinConfiguration);
  1516. TTerminalQueue * Queue;
  1517. for (int Index = 0; Index < Count; Index++)
  1518. {
  1519. DebugAssert(Sessions[Index]->Log);
  1520. Sessions[Index]->Log->ReflectSettings();
  1521. Sessions[Index]->ActionLog->ReflectSettings();
  1522. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1523. SetQueueConfiguration(Queue);
  1524. }
  1525. if (ScpExplorer)
  1526. {
  1527. ScpExplorer->ConfigurationChanged();
  1528. }
  1529. }
  1530. //---------------------------------------------------------------------------
  1531. void __fastcall TTerminalManager::ConfigurationChange(TObject * /*Sender*/)
  1532. {
  1533. if (FMainThread == GetCurrentThreadId())
  1534. {
  1535. DoConfigurationChange();
  1536. }
  1537. else
  1538. {
  1539. TGuard Guard(FChangeSection.get());
  1540. FPendingConfigurationChange++;
  1541. }
  1542. }
  1543. //---------------------------------------------------------------------------
  1544. void __fastcall TTerminalManager::SessionReady()
  1545. {
  1546. UpdateScpExplorer();
  1547. ScpExplorer->SessionReady();
  1548. }
  1549. //---------------------------------------------------------------------------
  1550. TStrings * __fastcall TTerminalManager::GetSessionList()
  1551. {
  1552. FSessionList->Clear();
  1553. for (int i = 0; i < Count; i++)
  1554. {
  1555. TManagedTerminal * Terminal = Sessions[i];
  1556. UnicodeString Name = GetSessionTitle(Terminal, true);
  1557. FSessionList->AddObject(Name, Terminal);
  1558. }
  1559. return FSessionList;
  1560. }
  1561. //---------------------------------------------------------------------------
  1562. int __fastcall TTerminalManager::GetActiveSessionIndex()
  1563. {
  1564. return (ActiveSession != NULL) ? IndexOf(ActiveSession) : -1;
  1565. }
  1566. //---------------------------------------------------------------------------
  1567. void __fastcall TTerminalManager::SetActiveSessionIndex(int value)
  1568. {
  1569. ActiveSession = Sessions[value];
  1570. }
  1571. //---------------------------------------------------------------------------
  1572. UnicodeString TTerminalManager::GetPathForSessionTabName(const UnicodeString & Path)
  1573. {
  1574. UnicodeString Result = Path;
  1575. const int MaxPathLen = 16;
  1576. if ((WinConfiguration->SessionTabNameFormat == stnfShortPathTrunc) &&
  1577. (Result.Length() > MaxPathLen))
  1578. {
  1579. Result = Result.SubString(1, MaxPathLen - 2) + Ellipsis;
  1580. }
  1581. return Result;
  1582. }
  1583. //---------------------------------------------------------------------------
  1584. UnicodeString __fastcall TTerminalManager::GetSessionTitle(TManagedTerminal * Session, bool Unique)
  1585. {
  1586. UnicodeString Result;
  1587. if (!Session->LocalBrowser)
  1588. {
  1589. Result = Session->SessionData->SessionName;
  1590. if (Unique &&
  1591. (WinConfiguration->SessionTabNameFormat != stnfNone))
  1592. {
  1593. int Index = IndexOf(Session);
  1594. // not for background transfer sessions and disconnected sessions
  1595. if ((Index >= 0) && Session->Active)
  1596. {
  1597. for (int Index2 = 0; Index2 < Count; Index2++)
  1598. {
  1599. UnicodeString Name = Sessions[Index2]->SessionData->SessionName;
  1600. if ((Sessions[Index2] != Session) &&
  1601. Sessions[Index2]->Active &&
  1602. SameText(Name, Result))
  1603. {
  1604. UnicodeString Path = ExtractShortName(Session->CurrentDirectory, true);
  1605. if (!Path.IsEmpty())
  1606. {
  1607. Path = GetPathForSessionTabName(Path);
  1608. Result = FORMAT(L"%s (%s)", (Result, Path));
  1609. }
  1610. break;
  1611. }
  1612. }
  1613. }
  1614. }
  1615. }
  1616. else
  1617. {
  1618. // should happen only when closing
  1619. if (ScpExplorer != NULL)
  1620. {
  1621. Result = ScpExplorer->GetLocalBrowserSessionTitle(Session);
  1622. }
  1623. }
  1624. return Result;
  1625. }
  1626. //---------------------------------------------------------------------------
  1627. UnicodeString TTerminalManager::FormatTerminalNoteMessage(TManagedTerminal * Terminal, const UnicodeString & Message)
  1628. {
  1629. return FORMAT(L"%s: %s", (GetSessionTitle(Terminal, true), Message));
  1630. }
  1631. //---------------------------------------------------------------------------
  1632. UnicodeString __fastcall TTerminalManager::GetActiveSessionAppTitle()
  1633. {
  1634. UnicodeString Result;
  1635. if ((ActiveSession != NULL) && !ActiveSession->LocalBrowser)
  1636. {
  1637. Result = GetSessionTitle(ActiveSession, false);
  1638. }
  1639. return Result;
  1640. }
  1641. //---------------------------------------------------------------------------
  1642. TTerminalQueue * __fastcall TTerminalManager::GetActiveQueue()
  1643. {
  1644. TTerminalQueue * Result = NULL;
  1645. if (ActiveSession != NULL)
  1646. {
  1647. Result = reinterpret_cast<TTerminalQueue *>(FQueues->Items[ActiveSessionIndex]);
  1648. }
  1649. return Result;
  1650. }
  1651. //---------------------------------------------------------------------------
  1652. void __fastcall TTerminalManager::CycleTerminals(bool Forward)
  1653. {
  1654. if (Count > 0)
  1655. {
  1656. int Index = ActiveSessionIndex;
  1657. Index += Forward ? 1 : -1;
  1658. if (Index < 0)
  1659. {
  1660. Index = Count-1;
  1661. }
  1662. else if (Index >= Count)
  1663. {
  1664. Index = 0;
  1665. }
  1666. ActiveSessionIndex = Index;
  1667. }
  1668. }
  1669. //---------------------------------------------------------------------------
  1670. bool __fastcall TTerminalManager::CanOpenInPutty()
  1671. {
  1672. return (ActiveTerminal != NULL) && !GUIConfiguration->PuttyPath.Trim().IsEmpty();
  1673. }
  1674. //---------------------------------------------------------------------------
  1675. void __fastcall TTerminalManager::OpenInPutty()
  1676. {
  1677. Configuration->Usage->Inc(L"OpenInPutty");
  1678. TSessionData * Data = NULL;
  1679. try
  1680. {
  1681. // Is NULL on the first session when called from ConnectActiveTerminal()
  1682. // due to WinConfiguration->AutoOpenInPutty
  1683. if (ScpExplorer != NULL)
  1684. {
  1685. Data = ScpExplorer->CloneCurrentSessionData();
  1686. }
  1687. else
  1688. {
  1689. Data = new TSessionData(L"");
  1690. DebugAssert(ActiveTerminal != NULL);
  1691. Data->Assign(ActiveTerminal->SessionData);
  1692. ActiveTerminal->UpdateSessionCredentials(Data);
  1693. }
  1694. if (ActiveTerminal->TunnelLocalPortNumber != 0)
  1695. {
  1696. Data->ConfigureTunnel(ActiveTerminal->TunnelLocalPortNumber);
  1697. }
  1698. OpenSessionInPutty(Data);
  1699. }
  1700. __finally
  1701. {
  1702. delete Data;
  1703. }
  1704. }
  1705. //---------------------------------------------------------------------------
  1706. void __fastcall TTerminalManager::NewSession(
  1707. const UnicodeString & SessionUrl, bool ReloadSessions, TForm * LinkedForm, bool ReplaceExisting)
  1708. {
  1709. if (ReloadSessions)
  1710. {
  1711. StoredSessions->Reload();
  1712. }
  1713. std::unique_ptr<TObjectList> DataList;
  1714. bool Retry;
  1715. do
  1716. {
  1717. Retry = false;
  1718. if (!DataList) // first round
  1719. {
  1720. DataList.reset(new TObjectList());
  1721. UnicodeString DownloadFile; // unused
  1722. GetLoginData(SessionUrl, NULL, DataList.get(), DownloadFile, true, LinkedForm);
  1723. }
  1724. else
  1725. {
  1726. if (!DoLoginDialog(DataList.get(), LinkedForm))
  1727. {
  1728. Abort(); // As GetLoginData would do
  1729. }
  1730. }
  1731. if (DataList->Count > 0)
  1732. {
  1733. if (ReplaceExisting)
  1734. {
  1735. // Tested for only the implicit Commanders' local browser
  1736. DebugAssert((Count == 0) || ((Count == 1) && Sessions[0]->LocalBrowser));
  1737. TAutoNestingCounter UpdatingCounter(FUpdating); // prevent tab flicker
  1738. FreeAll();
  1739. }
  1740. TManagedTerminal * ANewSession = NewSessions(DataList.get());
  1741. bool AdHoc = (DataList->Count == 1) && (StoredSessions->FindSame(reinterpret_cast<TSessionData *>(DataList->Items[0])) == NULL);
  1742. bool CanRetry = SessionUrl.IsEmpty() && AdHoc;
  1743. bool ShowLoginWhenNoSession = WinConfiguration->ShowLoginWhenNoSession;
  1744. if (CanRetry)
  1745. {
  1746. // we will show our own login dialog, so prevent opening an empty one
  1747. WinConfiguration->ShowLoginWhenNoSession = false;
  1748. }
  1749. try
  1750. {
  1751. ActiveSession = ANewSession;
  1752. }
  1753. __finally
  1754. {
  1755. if (CanRetry) // do not reset the value, unless really needed, as it can theoretically be changed meanwhile by the user
  1756. {
  1757. WinConfiguration->ShowLoginWhenNoSession = ShowLoginWhenNoSession;
  1758. }
  1759. }
  1760. Retry = CanRetry && (ActiveSession != ANewSession);
  1761. }
  1762. }
  1763. while (Retry);
  1764. }
  1765. //---------------------------------------------------------------------------
  1766. void TTerminalManager::StartInactiveTerminalReconnect(TManagedTerminal * Terminal)
  1767. {
  1768. ReconnectingTerminal(Terminal);
  1769. Terminal->NextInactiveReconnect = TDateTime(); // just in case
  1770. FReconnectingInactiveTerminal = Terminal;
  1771. DebugAssert(Terminal->TerminalThread == NULL);
  1772. TTerminalThread * TerminalThread = CreateTerminalThread(Terminal);
  1773. Terminal->TerminalThread = TerminalThread;
  1774. TerminalThread->AllowAbandon = true;
  1775. TerminalThread->StartTerminalReopenNonInteractive();
  1776. FReconnectingNote = FormatTerminalNoteMessage(Terminal, LoadStr(SESSION_RECONNECTING));
  1777. ScpExplorer->PostNote(FReconnectingNote);
  1778. }
  1779. //---------------------------------------------------------------------------
  1780. void TTerminalManager::CheckInactiveTerminalReconnect()
  1781. {
  1782. TManagedTerminal * Terminal = DebugNotNull(FReconnectingInactiveTerminal);
  1783. TTerminalThread * TerminalThread = DebugNotNull(Terminal->TerminalThread);
  1784. TTerminalReopenResult ReopenResult = TerminalThread->IsTerminalReopenComplete();
  1785. UnicodeString SessionName = Terminal->SessionData->SessionName;
  1786. if (ReopenResult == trrPending)
  1787. {
  1788. AppLog(FORMAT(L"Inactive session %s is still being reconnected", (SessionName)));
  1789. }
  1790. else
  1791. {
  1792. try
  1793. {
  1794. DebugCheck(TerminalThread->Release());
  1795. }
  1796. __finally
  1797. {
  1798. ReconnectedTerminal(Terminal);
  1799. Terminal->TerminalThread = NULL;
  1800. FReconnectingInactiveTerminal = NULL;
  1801. }
  1802. if (ReopenResult == trrSucceeded)
  1803. {
  1804. AppLog(FORMAT(L"Inactive session %s was reconnected", (SessionName)));
  1805. ScpExplorer->CancelNote(FReconnectingNote);
  1806. ScpExplorer->InactiveTerminalNotify(Terminal, LoadStr(SESSION_RECONNECTED), qtInformation);
  1807. }
  1808. else
  1809. {
  1810. if (ReopenResult == trrFailed)
  1811. {
  1812. // in case it was disabled meanwhile
  1813. if (GUIConfiguration->SessionReopenAutoInactive)
  1814. {
  1815. int Interval = 2 * GUIConfiguration->SessionReopenAutoIdle;
  1816. AppLog(FORMAT(L"Inactive session %s failed to reconnect, will try again in %d ms", (SessionName, Interval)));
  1817. // Might want to consider SessionReopenTimeout
  1818. Terminal->NextInactiveReconnect = IncMilliSecond(Now(), Interval);
  1819. }
  1820. else
  1821. {
  1822. Terminal->NextInactiveReconnect = TDateTime();
  1823. }
  1824. }
  1825. else if (ReopenResult == trrNeedsInteraction)
  1826. {
  1827. AppLog(FORMAT(L"Inactive session %s needs interaction", (SessionName)));
  1828. ScpExplorer->CancelNote(FReconnectingNote);
  1829. ScpExplorer->InactiveTerminalNotify(Terminal, LoadStr(SESSION_NEED_INTERACTION), qtInformation);
  1830. Terminal->NextInactiveReconnect = TDateTime();
  1831. }
  1832. try
  1833. {
  1834. if (Terminal->Active)
  1835. {
  1836. Terminal->Close();
  1837. }
  1838. }
  1839. catch (...)
  1840. {
  1841. }
  1842. }
  1843. FReconnectingNote = EmptyStr;
  1844. }
  1845. }
  1846. //---------------------------------------------------------------------------
  1847. void __fastcall TTerminalManager::Idle(bool SkipCurrentTerminal)
  1848. {
  1849. if (FPendingConfigurationChange > 0) // optimization
  1850. {
  1851. bool Changed = false;
  1852. {
  1853. TGuard Guard(FChangeSection.get());
  1854. if (DebugAlwaysTrue(FPendingConfigurationChange > 0))
  1855. {
  1856. FPendingConfigurationChange--;
  1857. Changed = true;
  1858. }
  1859. }
  1860. if (Changed)
  1861. {
  1862. DoConfigurationChange();
  1863. }
  1864. }
  1865. for (int Index = 0; Index < Count; Index++)
  1866. {
  1867. TManagedTerminal * Terminal = Sessions[Index];
  1868. try
  1869. {
  1870. if (Terminal == FReconnectingInactiveTerminal)
  1871. {
  1872. CheckInactiveTerminalReconnect();
  1873. }
  1874. else if (!SkipCurrentTerminal || (Terminal != ActiveTerminal))
  1875. {
  1876. // make sure Idle is called on the thread that runs the terminal
  1877. if (Terminal->TerminalThread != NULL)
  1878. {
  1879. Terminal->TerminalThread->Idle();
  1880. }
  1881. else
  1882. {
  1883. if (Terminal->Active)
  1884. {
  1885. Terminal->Idle();
  1886. }
  1887. else if ((Terminal != ActiveTerminal) &&
  1888. GUIConfiguration->SessionReopenAutoInactive &&
  1889. (FReconnectingInactiveTerminal == NULL) &&
  1890. (Terminal->NextInactiveReconnect != TDateTime()) &&
  1891. (Terminal->NextInactiveReconnect < Now()))
  1892. {
  1893. StartInactiveTerminalReconnect(Terminal);
  1894. }
  1895. }
  1896. if (Terminal->Active)
  1897. {
  1898. DebugAssert(Index < FQueues->Count);
  1899. if (Index < FQueues->Count)
  1900. {
  1901. reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index])->Idle();
  1902. }
  1903. }
  1904. }
  1905. }
  1906. catch(Exception & E)
  1907. {
  1908. if (Terminal == ActiveTerminal)
  1909. {
  1910. // throw further, so that the exception is handled in proper place
  1911. // (particularly in broken-transfer reconnect handler, bug 72)
  1912. throw;
  1913. }
  1914. else
  1915. {
  1916. // we may not have inactive terminal, unless there is a explorer,
  1917. // also Idle is called from explorer anyway
  1918. if (DebugAlwaysTrue(ScpExplorer != NULL))
  1919. {
  1920. ScpExplorer->InactiveTerminalNotify(Terminal, EmptyStr, qtError, &E);
  1921. }
  1922. if (!Terminal->Active)
  1923. {
  1924. // if session is lost, save the error message and rethrow it
  1925. // once the terminal gets activated
  1926. Terminal->InactiveTerminationMessage = E.Message;
  1927. Terminal->NextInactiveReconnect = IncMilliSecond(Now(), GUIConfiguration->SessionReopenAutoIdle);
  1928. }
  1929. }
  1930. }
  1931. }
  1932. TTerminalQueue * QueueWithEvent;
  1933. do
  1934. {
  1935. QueueWithEvent = NULL;
  1936. TQueueEvent QueueEvent = TQueueEvent(); // shut up
  1937. {
  1938. TGuard Guard(FQueueSection);
  1939. if (!FQueueEvents.empty())
  1940. {
  1941. QueueWithEvent = FQueueEvents[0].first;
  1942. QueueEvent = FQueueEvents[0].second;
  1943. FQueueEvents.erase(FQueueEvents.begin());
  1944. }
  1945. }
  1946. if (QueueWithEvent != NULL)
  1947. {
  1948. int Index = FQueues->IndexOf(QueueWithEvent);
  1949. // the session may not exist anymore
  1950. if (Index >= 0)
  1951. {
  1952. TManagedTerminal * Terminal = Sessions[Index];
  1953. // we can hardly have a queue event without explorer
  1954. DebugAssert(ScpExplorer != NULL);
  1955. if (ScpExplorer != NULL)
  1956. {
  1957. ScpExplorer->QueueEvent(Terminal, QueueWithEvent, QueueEvent);
  1958. }
  1959. }
  1960. }
  1961. }
  1962. while (QueueWithEvent != NULL);
  1963. }
  1964. //---------------------------------------------------------------------------
  1965. void __fastcall TTerminalManager::MasterPasswordPrompt()
  1966. {
  1967. if (GetCurrentThreadId() == MainThreadID)
  1968. {
  1969. if (!DoMasterPasswordDialog())
  1970. {
  1971. Abort();
  1972. }
  1973. }
  1974. else
  1975. {
  1976. // this can happen only when we keep cancelling all master password prompts
  1977. // as long as the sessing finally connects (session password has to be
  1978. // explictly typed in), and background transfer is started
  1979. Abort();
  1980. }
  1981. }
  1982. //---------------------------------------------------------------------------
  1983. void __fastcall TTerminalManager::Move(TTerminal * Source, TTerminal * Target)
  1984. {
  1985. int SourceIndex = IndexOf(Source);
  1986. int TargetIndex = IndexOf(Target);
  1987. TTerminalList::Move(SourceIndex, TargetIndex);
  1988. FQueues->Move(SourceIndex, TargetIndex);
  1989. DoSessionListChanged();
  1990. // when there are indexed sessions with the same name,
  1991. // the index may change when reordering the sessions
  1992. UpdateAppTitle();
  1993. }
  1994. //---------------------------------------------------------------------------
  1995. void __fastcall TTerminalManager::DoSessionListChanged()
  1996. {
  1997. if ((FScpExplorer != NULL) && !Updating)
  1998. {
  1999. FScpExplorer->SessionListChanged();
  2000. }
  2001. }
  2002. //---------------------------------------------------------------------------
  2003. void __fastcall TTerminalManager::SaveWorkspace(TList * DataList)
  2004. {
  2005. for (int Index = 0; Index < Count; Index++)
  2006. {
  2007. TManagedTerminal * ManagedTerminal = Sessions[Index];
  2008. TSessionData * Data = StoredSessions->SaveWorkspaceData(ManagedTerminal->StateData, Index);
  2009. if (ManagedTerminal->Active)
  2010. {
  2011. ManagedTerminal->UpdateSessionCredentials(Data);
  2012. }
  2013. DataList->Add(Data);
  2014. }
  2015. }
  2016. //---------------------------------------------------------------------------
  2017. bool TTerminalManager::IsOpenedTerminal(TTerminal * Terminal)
  2018. {
  2019. return
  2020. (Terminal != NULL) &&
  2021. Terminal->Active;
  2022. }
  2023. //---------------------------------------------------------------------------
  2024. bool TTerminalManager::IsAvailableTerminal(TTerminal * Terminal)
  2025. {
  2026. return
  2027. IsOpenedTerminal(Terminal) &&
  2028. !IsReconnectingTerminal(Terminal);
  2029. }
  2030. //---------------------------------------------------------------------------
  2031. bool TTerminalManager::IsReconnectingTerminal(TTerminal * Terminal)
  2032. {
  2033. return
  2034. (Terminal != NULL) &&
  2035. ((Terminal == FOpeningTerminal) || (Terminal == FReconnectingInactiveTerminal));
  2036. }
  2037. //---------------------------------------------------------------------------
  2038. bool TTerminalManager::IsAvailableTerminalForSite(TTerminal * Terminal, TSessionData * Data)
  2039. {
  2040. bool Result = IsAvailableTerminal(Terminal);
  2041. if (Result)
  2042. {
  2043. std::unique_ptr<TSessionData> TerminalData(Terminal->SessionData->Clone());
  2044. Terminal->UpdateSessionCredentials(TerminalData.get());
  2045. Result = TerminalData->IsSameSite(Data);
  2046. }
  2047. return Result;
  2048. }
  2049. //---------------------------------------------------------------------------
  2050. TManagedTerminal * __fastcall TTerminalManager::FindActiveTerminalForSite(TSessionData * Data)
  2051. {
  2052. TManagedTerminal * Result = NULL;
  2053. for (int Index = 0; (Result == NULL) && (Index < Count); Index++)
  2054. {
  2055. TManagedTerminal * Terminal = Sessions[Index];
  2056. if (IsAvailableTerminalForSite(Terminal, Data))
  2057. {
  2058. Result = Terminal;
  2059. }
  2060. }
  2061. return Result;
  2062. }
  2063. //---------------------------------------------------------------------------
  2064. TTerminalQueue * __fastcall TTerminalManager::FindQueueForTerminal(TTerminal * Terminal)
  2065. {
  2066. int Index = IndexOf(Terminal);
  2067. return reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  2068. }
  2069. //---------------------------------------------------------------------------
  2070. bool __fastcall TTerminalManager::UploadPublicKey(
  2071. TTerminal * Terminal, TSessionData * Data, UnicodeString & FileName)
  2072. {
  2073. std::unique_ptr<TOpenDialog> OpenDialog(new TOpenDialog(Application));
  2074. OpenDialog->Title = LoadStr(LOGIN_PUBLIC_KEY_TITLE);
  2075. OpenDialog->Filter = LoadStr(LOGIN_PUBLIC_KEY_FILTER);
  2076. OpenDialog->DefaultExt = PuttyKeyExt;
  2077. OpenDialog->FileName = FileName;
  2078. bool Result = OpenDialog->Execute();
  2079. if (Result)
  2080. {
  2081. Configuration->Usage->Inc(L"PublicKeyInstallation");
  2082. FileName = OpenDialog->FileName;
  2083. VerifyAndConvertKey(FileName, false);
  2084. bool AdHocTerminal = (Terminal == NULL);
  2085. std::unique_ptr<TTerminal> TerminalOwner;
  2086. if (AdHocTerminal)
  2087. {
  2088. DebugAssert(Data != NULL);
  2089. TAutoFlag KeepAuthenticateFormFlag(FKeepAuthenticateForm);
  2090. try
  2091. {
  2092. TerminalOwner.reset(CreateTerminal(Data));
  2093. Terminal = TerminalOwner.get();
  2094. SetupTerminal(Terminal);
  2095. Terminal->OnProgress = NULL;
  2096. Terminal->OnFinished = NULL;
  2097. DoConnectTerminal(Terminal, false, true);
  2098. }
  2099. catch (Exception &)
  2100. {
  2101. CloseAutheticateForm();
  2102. throw;
  2103. }
  2104. }
  2105. UnicodeString Installed;
  2106. try
  2107. {
  2108. UnicodeString SshImplementation = Terminal->GetSessionInfo().SshImplementation;
  2109. UnicodeString NotOpenSSHMessage = FMTLOAD(LOGIN_NOT_OPENSSH, (SshImplementation));
  2110. if (IsOpenSSH(SshImplementation) ||
  2111. (MessageDialog(NotOpenSSHMessage, qtConfirmation, qaOK | qaCancel, HELP_LOGIN_AUTHORIZED_KEYS) == qaOK))
  2112. {
  2113. // Ad-hoc terminal
  2114. if (FAuthenticateForm != NULL)
  2115. {
  2116. UnicodeString Comment;
  2117. bool UnusedHasCertificate;
  2118. GetPublicKeyLine(FileName, Comment, UnusedHasCertificate);
  2119. FAuthenticateForm->Log(FMTLOAD(LOGIN_PUBLIC_KEY_UPLOAD, (Comment)));
  2120. }
  2121. Installed = Terminal->UploadPublicKey(FileName);
  2122. }
  2123. }
  2124. __finally
  2125. {
  2126. CloseAutheticateForm(); // When uploading from Login dialog
  2127. }
  2128. if (!Installed.IsEmpty())
  2129. {
  2130. Terminal->LogEvent(L"Public key installation done.");
  2131. if (AdHocTerminal)
  2132. {
  2133. TerminalOwner.reset(NULL);
  2134. }
  2135. else
  2136. {
  2137. Terminal->Log->AddSeparator();
  2138. }
  2139. MessageDialog(Installed, qtInformation, qaOK, HELP_LOGIN_AUTHORIZED_KEYS);
  2140. }
  2141. }
  2142. return Result;
  2143. }
  2144. //---------------------------------------------------------------------------
  2145. bool TTerminalManager::IsUpdating()
  2146. {
  2147. return (FUpdating > 0);
  2148. }
  2149. //---------------------------------------------------------------------------
  2150. bool TTerminalManager::HookFatalExceptionMessageDialog(TMessageParams & Params)
  2151. {
  2152. bool Result =
  2153. DebugAlwaysTrue(ActiveTerminal != NULL) &&
  2154. DebugAlwaysTrue(Params.Timer == 0) &&
  2155. DebugAlwaysTrue(Params.TimerEvent == NULL) &&
  2156. DebugAlwaysTrue(FTerminalWithFatalExceptionTimer == NULL);
  2157. if (Result)
  2158. {
  2159. Params.Timer = MSecsPerSec / 4;
  2160. Params.TimerEvent = TerminalFatalExceptionTimer;
  2161. FTerminalWithFatalExceptionTimer = ActiveTerminal;
  2162. FTerminalReconnnecteScheduled = false;
  2163. }
  2164. return Result;
  2165. }
  2166. //---------------------------------------------------------------------------
  2167. void TTerminalManager::UnhookFatalExceptionMessageDialog()
  2168. {
  2169. DebugAssert(FTerminalWithFatalExceptionTimer != NULL);
  2170. FTerminalWithFatalExceptionTimer = NULL;
  2171. }
  2172. //---------------------------------------------------------------------------
  2173. bool TTerminalManager::ScheduleTerminalReconnnect(TTerminal * Terminal)
  2174. {
  2175. bool Result = (FTerminalWithFatalExceptionTimer == Terminal);
  2176. if (Result)
  2177. {
  2178. FTerminalReconnnecteScheduled = true;
  2179. }
  2180. return Result;
  2181. }
  2182. //---------------------------------------------------------------------------
  2183. void __fastcall TTerminalManager::TerminalFatalExceptionTimer(unsigned int & Result)
  2184. {
  2185. if (FTerminalReconnnecteScheduled)
  2186. {
  2187. Result = qaRetry;
  2188. FTerminalReconnnecteScheduled = false;
  2189. }
  2190. }
  2191. //---------------------------------------------------------------------------
  2192. TBitmap * TTerminalManager::ThumbnailNeeded(TManagedTerminal * Terminal, int Index, TRemoteFile * File, const TSize & Size)
  2193. {
  2194. TGuard Guard(Terminal->ThumbnailsSection.get());
  2195. TRemoteThumbnailsMap::iterator I = Terminal->Thumbnails.find(Index);
  2196. TBitmap * Result;
  2197. if ((I != Terminal->Thumbnails.end()) &&
  2198. UnixSamePath(File->FileName, I->second.FileName) &&
  2199. (I->second.ThumbnailSize == Size))
  2200. {
  2201. Result = I->second.Thumbnail;
  2202. }
  2203. else
  2204. {
  2205. TRemoteThumbnailNeeded ThumbnailNeeded;
  2206. ThumbnailNeeded.Index = Index;
  2207. ThumbnailNeeded.File = File->Duplicate();
  2208. ThumbnailNeeded.ThumbnailSize = Size;
  2209. Terminal->ThumbnailsQueue.push_back(ThumbnailNeeded);
  2210. if (I != Terminal->Thumbnails.end())
  2211. {
  2212. delete I->second.Thumbnail;
  2213. }
  2214. // Prevent duplicates in queue
  2215. TRemoteThumbnailData ThumbnailData;
  2216. ThumbnailData.FileName = File->FileName;
  2217. ThumbnailData.Thumbnail = NULL;
  2218. ThumbnailData.ThumbnailSize = Size;
  2219. Terminal->Thumbnails.insert(std::make_pair(Index, ThumbnailData));
  2220. if (Terminal->ThumbnailsEnabled)
  2221. {
  2222. NeedThumbnailDownloadQueueItem(Terminal);
  2223. }
  2224. Result = NULL;
  2225. }
  2226. return Result;
  2227. }
  2228. //---------------------------------------------------------------------------
  2229. void TTerminalManager::NeedThumbnailDownloadQueueItem(TManagedTerminal * ATerminal)
  2230. {
  2231. // Expects that ThumbnailsSection is already locked
  2232. if (ATerminal->ThumbnailDownloadQueueItem == NULL)
  2233. {
  2234. ATerminal->ThumbnailDownloadQueueItem = ScpExplorer->AddThumbnailDownloadQueueItem(ATerminal);
  2235. }
  2236. }
  2237. //---------------------------------------------------------------------------
  2238. void TTerminalManager::TerminalLoadedDirectory(TManagedTerminal * ATerminal)
  2239. {
  2240. DebugAssert(ActiveTerminal == ATerminal);
  2241. TGuard Guard(ATerminal->ThumbnailsSection.get());
  2242. AppLog(L"Loaded directory");
  2243. ATerminal->ThumbnailsEnabled = true;
  2244. if (!ATerminal->ThumbnailsQueue.empty())
  2245. {
  2246. NeedThumbnailDownloadQueueItem(ATerminal);
  2247. }
  2248. }
  2249. //---------------------------------------------------------------------------
  2250. //---------------------------------------------------------------------------
  2251. TThumbnailDownloadQueueItem::TThumbnailDownloadQueueItem(
  2252. TCustomScpExplorerForm * ScpExplorer, TManagedTerminal * Terminal, const UnicodeString & SourceDir,
  2253. const UnicodeString & TargetDir, const TCopyParamType * CopyParam) :
  2254. TTransferQueueItem(Terminal, NULL, TargetDir, CopyParam, cpNoConfirmation | cpTemporary, osRemote, true, false),
  2255. FManagedTerminal(Terminal), FScpExplorer(ScpExplorer)
  2256. {
  2257. FInfo->Source = SourceDir;
  2258. }
  2259. //---------------------------------------------------------------------------
  2260. __fastcall TThumbnailDownloadQueueItem::~TThumbnailDownloadQueueItem()
  2261. {
  2262. RecursiveDeleteFile(ExcludeTrailingBackslash(FTargetDir));
  2263. }
  2264. //---------------------------------------------------------------------------
  2265. bool TThumbnailDownloadQueueItem::Continue()
  2266. {
  2267. return !IsExecutionCancelled() && FManagedTerminal->ThumbnailsEnabled;
  2268. }
  2269. //---------------------------------------------------------------------------
  2270. bool TThumbnailDownloadQueueItem::CheckQueueFront(int Index, const UnicodeString & FileName, TSize ThumbnailSize)
  2271. {
  2272. TRemoteThumbnailsQueue & ThumbnailsQueue = FManagedTerminal->ThumbnailsQueue;
  2273. bool Result = !ThumbnailsQueue.empty();
  2274. if (Result)
  2275. {
  2276. const TRemoteThumbnailNeeded & ThumbnailNeeded = ThumbnailsQueue.front();
  2277. Result =
  2278. (ThumbnailNeeded.Index == Index) &&
  2279. (ThumbnailNeeded.File->FullFileName == FileName) &&
  2280. (ThumbnailNeeded.ThumbnailSize == ThumbnailSize);
  2281. }
  2282. return Result;
  2283. }
  2284. //---------------------------------------------------------------------------
  2285. void __fastcall TThumbnailDownloadQueueItem::DoTransferExecute(TTerminal * Terminal, TParallelOperation *)
  2286. {
  2287. TCriticalSection * Section = FManagedTerminal->ThumbnailsSection.get();
  2288. TGuard Guard(Section);
  2289. UnicodeString LastSourceDir;
  2290. TRemoteThumbnailsQueue & ThumbnailsQueue = FManagedTerminal->ThumbnailsQueue;
  2291. while (Continue() && !ThumbnailsQueue.empty())
  2292. {
  2293. const TRemoteThumbnailNeeded & ThumbnailNeeded = ThumbnailsQueue.front();
  2294. FManagedTerminal->ThumbnailVisibleResult = -1;
  2295. int Index = ThumbnailNeeded.Index;
  2296. std::unique_ptr<TRemoteFile> File(ThumbnailNeeded.File->Duplicate());
  2297. TSize ThumbnailSize = ThumbnailNeeded.ThumbnailSize;
  2298. UnicodeString FileName = File->FullFileName.Unique();
  2299. AppLogFmt(L"Retrieving thumbnail for %s", (FileName));
  2300. FManagedTerminal->ThumbnailVisibleResult = -1;
  2301. FScpExplorer->PostThumbnailVisibleQueueQuery(Index, FileName);
  2302. LastSourceDir = UnixExtractFileDir(FileName);
  2303. {
  2304. TGuard ItemGuard(FSection);
  2305. FInfo->Source = FileName;
  2306. }
  2307. while (Continue() &&
  2308. (FManagedTerminal->ThumbnailVisibleResult < 0))
  2309. {
  2310. TUnguard Unguard(Section);
  2311. Sleep(10);
  2312. }
  2313. if (Continue())
  2314. {
  2315. if (FManagedTerminal->ThumbnailVisibleResult == 0)
  2316. {
  2317. DebugAssert(ThumbnailsQueue.empty() || (&ThumbnailsQueue.front() != &ThumbnailNeeded));
  2318. }
  2319. else if (DebugAlwaysTrue(CheckQueueFront(Index, FileName, ThumbnailSize)))
  2320. {
  2321. std::unique_ptr<TStringList> Files(new TStringList());
  2322. Files->AddObject(FileName, File.get());
  2323. std::unique_ptr<TBitmap> Thumbnail;
  2324. {
  2325. TUnguard Unguard(Section);
  2326. Terminal->CopyToLocal(Files.get(), FTargetDir, FCopyParam, FParams, NULL);
  2327. UnicodeString LocalPath =
  2328. TPath::Combine(FTargetDir, Terminal->ChangeFileName(FCopyParam, UnixExtractFileName(FileName), osRemote, false));
  2329. Thumbnail.reset(GetThumbnail(LocalPath, ThumbnailSize));
  2330. }
  2331. if (CheckQueueFront(Index, FileName, ThumbnailSize))
  2332. {
  2333. TRemoteThumbnailsMap::iterator I = FManagedTerminal->Thumbnails.find(Index);
  2334. if (DebugAlwaysTrue(I != FManagedTerminal->Thumbnails.end()))
  2335. {
  2336. TRemoteThumbnailData & RemoteThumbnailData = I->second;
  2337. if (DebugAlwaysTrue(RemoteThumbnailData.FileName == UnixExtractFileName(FileName)) &&
  2338. DebugAlwaysTrue(RemoteThumbnailData.ThumbnailSize == ThumbnailSize) &&
  2339. DebugAlwaysTrue(RemoteThumbnailData.Thumbnail == NULL))
  2340. {
  2341. RemoteThumbnailData.Thumbnail = Thumbnail.release();
  2342. FManagedTerminal->PopThumbnailQueue();
  2343. FScpExplorer->PostThumbnailDrawRequest(Index);
  2344. }
  2345. }
  2346. }
  2347. }
  2348. }
  2349. }
  2350. {
  2351. TGuard ItemGuard(FSection);
  2352. FInfo->Source = LastSourceDir;
  2353. }
  2354. FManagedTerminal->ThumbnailDownloadQueueItem = NULL;
  2355. }