TerminalManager.cpp 73 KB

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