TerminalManager.cpp 81 KB

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