TerminalManager.cpp 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480
  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 __fastcall TTerminalManager::FreeTerminal(TTerminal * Terminal)
  707. {
  708. TTerminal * ATerminal = Terminal;
  709. bool IsActiveSession = ((ActiveSession != NULL) && (Terminal == ActiveSession));
  710. try
  711. {
  712. if (!IsActiveSession)
  713. {
  714. // For active session, done by DoSetActiveSession below.
  715. // For inactive session, needs to be done here before potentially abandoning the session.
  716. SaveTerminal(Terminal);
  717. }
  718. TManagedTerminal * ManagedSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  719. // we want the Login dialog to open on auto-workspace name,
  720. // as set in TCustomScpExplorerForm::FormClose
  721. if ((!FDestroying || !WinConfiguration->AutoSaveWorkspace) && !ManagedSession->LocalBrowser)
  722. {
  723. if (StoredSessions->FindSame(Terminal->SessionData) != NULL)
  724. {
  725. WinConfiguration->LastStoredSession = Terminal->SessionData->Name;
  726. }
  727. }
  728. if (ScpExplorer != NULL)
  729. {
  730. ScpExplorer->TerminalRemoved(Terminal);
  731. }
  732. if (ManagedSession == FReconnectingInactiveTerminal)
  733. {
  734. DebugAssert(!IsActiveSession);
  735. AppLog(L"Cancelling background reconnect before closing session");
  736. TTerminalThread * TerminalThread = DebugNotNull(ManagedSession->TerminalThread);
  737. DebugAssert(TerminalThread->AllowAbandon);
  738. TerminalThread->Cancel();
  739. while (!TerminalThread->Abandoned())
  740. {
  741. Sleep(50);
  742. }
  743. if (!TerminalThread->Release())
  744. {
  745. AppLog(L"Abandoned background reconnect");
  746. TerminalThread->Terminate();
  747. Terminal = NULL;
  748. }
  749. else
  750. {
  751. AppLog(L"Background reconnect stopped");
  752. ManagedSession->TerminalThread = NULL;
  753. }
  754. FReconnectingInactiveTerminal = NULL;
  755. }
  756. else if (Terminal->Active)
  757. {
  758. Terminal->Close();
  759. }
  760. }
  761. __finally
  762. {
  763. int Index = IndexOf(ATerminal);
  764. Extract(ATerminal);
  765. TTerminalQueue * Queue;
  766. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  767. FQueues->Delete(Index);
  768. if (IsActiveSession)
  769. {
  770. TManagedTerminal * NewActiveTerminal;
  771. bool LastTerminalClosed = false;
  772. if (FDestroying)
  773. {
  774. NewActiveTerminal = NULL;
  775. }
  776. else
  777. {
  778. if (Count > 0)
  779. {
  780. NewActiveTerminal = Sessions[Index < Count ? Index : Index - 1];
  781. if (!NewActiveTerminal->Active && !NewActiveTerminal->Disconnected)
  782. {
  783. NewActiveTerminal->Disconnected = true;
  784. NewActiveTerminal->DisconnectedTemporarily = true;
  785. }
  786. }
  787. else
  788. {
  789. NewActiveTerminal = NULL;
  790. LastTerminalClosed = true;
  791. if (ScpExplorer != NULL)
  792. {
  793. TAutoNestingCounter UpdatingCounter(FUpdating); // prevent tab flicker
  794. NewActiveTerminal = ScpExplorer->GetReplacementForLastSession();
  795. }
  796. }
  797. }
  798. DoSetActiveSession(NewActiveTerminal, false, LastTerminalClosed);
  799. }
  800. // only now all references to/from queue (particularly events to explorer)
  801. // are cleared
  802. delete Queue;
  803. delete Terminal; // noop if abandoned
  804. DoSessionListChanged();
  805. }
  806. }
  807. //---------------------------------------------------------------------------
  808. void TTerminalManager::UpdateScpExplorer(TManagedTerminal * Session, TTerminalQueue * Queue)
  809. {
  810. FScpExplorer->ManagedSession = Session;
  811. FScpExplorer->Queue = Queue;
  812. }
  813. //---------------------------------------------------------------------------
  814. void TTerminalManager::UpdateScpExplorer()
  815. {
  816. UpdateScpExplorer(ActiveSession, ActiveQueue);
  817. }
  818. //---------------------------------------------------------------------------
  819. void __fastcall TTerminalManager::SetScpExplorer(TCustomScpExplorerForm * value)
  820. {
  821. if (ScpExplorer != value)
  822. {
  823. // changing explorer is not supported yet
  824. DebugAssert(!ScpExplorer || !value);
  825. FScpExplorer = value;
  826. if (FScpExplorer)
  827. {
  828. UpdateScpExplorer();
  829. UpdateTaskbarList();
  830. }
  831. }
  832. }
  833. //---------------------------------------------------------------------------
  834. TManagedTerminal * TTerminalManager::GetActiveTerminal()
  835. {
  836. TManagedTerminal * Result;
  837. if ((ActiveSession != NULL) && !ActiveSession->LocalBrowser)
  838. {
  839. Result = ActiveSession;
  840. }
  841. else
  842. {
  843. Result = NULL;
  844. }
  845. return Result;
  846. }
  847. //---------------------------------------------------------------------------
  848. void __fastcall TTerminalManager::SetActiveSession(TManagedTerminal * value)
  849. {
  850. DoSetActiveSession(value, false, false);
  851. }
  852. //---------------------------------------------------------------------------
  853. void __fastcall TTerminalManager::SetActiveTerminalWithAutoReconnect(TManagedTerminal * value)
  854. {
  855. DoSetActiveSession(value, true, false);
  856. }
  857. //---------------------------------------------------------------------------
  858. void __fastcall TTerminalManager::DoSetActiveSession(TManagedTerminal * value, bool AutoReconnect, bool LastTerminalClosed)
  859. {
  860. if (ActiveSession != value)
  861. {
  862. if (NonVisualDataModule != NULL)
  863. {
  864. NonVisualDataModule->StartBusy();
  865. }
  866. void * Focus = NULL;
  867. try
  868. {
  869. // here used to be call to TCustomScpExporer::UpdateSessionData (now UpdateSession)
  870. // but it seems to be duplicate to call from TCustomScpExporer::SessionChanging
  871. TManagedTerminal * PActiveSession = ActiveSession;
  872. FActiveSession = value;
  873. if (ScpExplorer)
  874. {
  875. Focus = ScpExplorer->SaveFocus();
  876. if ((ActiveSession != NULL) &&
  877. ((ActiveSession->Status == ssOpened) || ActiveSession->Disconnected || ActiveSession->LocalBrowser))
  878. {
  879. SessionReady();
  880. }
  881. else
  882. {
  883. UpdateScpExplorer(NULL, NULL);
  884. }
  885. }
  886. UpdateAppTitle();
  887. if (PActiveSession != NULL)
  888. {
  889. PActiveSession->DisableThumbnails();
  890. if (PActiveSession->DisconnectedTemporarily && DebugAlwaysTrue(PActiveSession->Disconnected))
  891. {
  892. PActiveSession->Disconnected = false;
  893. PActiveSession->DisconnectedTemporarily = false;
  894. }
  895. if (!PActiveSession->Active)
  896. {
  897. SaveTerminal(PActiveSession);
  898. }
  899. }
  900. if (ActiveSession != NULL)
  901. {
  902. if ((FReconnectingInactiveTerminal == ActiveSession) &&
  903. DebugAlwaysTrue(ScpExplorer != NULL) &&
  904. DebugAlwaysTrue(FReconnectingInactiveTerminal->TerminalThread != NULL))
  905. {
  906. DebugAssert(FTerminalPendingAction == tpNull); // the only assumed and tested scenario
  907. ReconnectActiveTerminal();
  908. }
  909. else if (!ActiveSession->Active &&
  910. !ActiveSession->InactiveTerminationMessage.IsEmpty() &&
  911. DebugAlwaysTrue(!ActiveSession->LocalBrowser))
  912. {
  913. UnicodeString Message = ActiveSession->InactiveTerminationMessage;
  914. ActiveSession->InactiveTerminationMessage = EmptyStr;
  915. if (AutoReconnect || GUIConfiguration->SessionReopenAutoInactive)
  916. {
  917. ReconnectActiveTerminal();
  918. }
  919. else
  920. {
  921. // finally show pending terminal message,
  922. // this gives user also possibility to reconnect
  923. std::unique_ptr<ESshFatal> E(new ESshFatal(NULL, Message));
  924. E->InactiveTerminationMessage = true;
  925. ActiveTerminal->ShowExtendedException(E.get());
  926. }
  927. }
  928. // LastTerminalClosed is true only for a replacement local session,
  929. // and it should never happen that it fails to be activated
  930. if (LastTerminalClosed && DebugAlwaysFalse(value != ActiveSession))
  931. {
  932. LastTerminalClosed = false; // just in case
  933. }
  934. }
  935. else
  936. {
  937. LastTerminalClosed = true;
  938. }
  939. if (LastTerminalClosed && !Updating && (ScpExplorer != NULL))
  940. {
  941. ScpExplorer->LastTerminalClosed();
  942. }
  943. if ((ActiveSession != NULL) &&
  944. !ActiveSession->Active && !ActiveSession->Disconnected && !ActiveSession->LocalBrowser)
  945. {
  946. DebugAssert(ActiveSession->InactiveTerminationMessage.IsEmpty());
  947. ConnectActiveTerminal();
  948. }
  949. }
  950. __finally
  951. {
  952. if (NonVisualDataModule != NULL)
  953. {
  954. NonVisualDataModule->EndBusy();
  955. }
  956. if ((Focus != NULL) && DebugAlwaysTrue(ScpExplorer != NULL))
  957. {
  958. ScpExplorer->RestoreFocus(Focus);
  959. }
  960. }
  961. }
  962. }
  963. //---------------------------------------------------------------------------
  964. void __fastcall TTerminalManager::QueueStatusUpdated()
  965. {
  966. UpdateAppTitle();
  967. }
  968. //---------------------------------------------------------------------------
  969. bool __fastcall TTerminalManager::ShouldDisplayQueueStatusOnAppTitle()
  970. {
  971. bool Result = IsApplicationMinimized();
  972. if (!Result && (ScpExplorer != NULL))
  973. {
  974. HWND Window = GetActiveWindow();
  975. Window = GetAncestor(Window, GA_ROOTOWNER);
  976. Result = (ScpExplorer->Handle != Window);
  977. }
  978. return Result;
  979. }
  980. //---------------------------------------------------------------------------
  981. UnicodeString __fastcall TTerminalManager::FormatFormCaptionWithSession(TCustomForm * Form, const UnicodeString & Caption)
  982. {
  983. return FormatFormCaption(Form, Caption, GetActiveSessionAppTitle());
  984. }
  985. //---------------------------------------------------------------------------
  986. UnicodeString __fastcall TTerminalManager::GetAppProgressTitle()
  987. {
  988. UnicodeString Result;
  989. UnicodeString QueueProgressTitle;
  990. UnicodeString ProgressTitle = !FProgressTitle.IsEmpty() ? FProgressTitle : ScpExplorer->GetProgressTitle();
  991. if (!FForegroundProgressTitle.IsEmpty())
  992. {
  993. Result = FForegroundProgressTitle;
  994. }
  995. else if (!ProgressTitle.IsEmpty() && !ForegroundTask())
  996. {
  997. Result = ProgressTitle;
  998. }
  999. else if (ShouldDisplayQueueStatusOnAppTitle() &&
  1000. !(QueueProgressTitle = ScpExplorer->GetQueueProgressTitle()).IsEmpty())
  1001. {
  1002. Result = QueueProgressTitle;
  1003. }
  1004. return Result;
  1005. }
  1006. //---------------------------------------------------------------------------
  1007. void __fastcall TTerminalManager::UpdateAppTitle()
  1008. {
  1009. if (ScpExplorer)
  1010. {
  1011. TForm * MainForm = GetMainForm();
  1012. if (MainForm != ScpExplorer)
  1013. {
  1014. // triggers caption update for some forms
  1015. MainForm->Perform(WM_MANAGES_CAPTION, 0, 0);
  1016. }
  1017. UnicodeString NewTitle = FormatMainFormCaption(GetActiveSessionAppTitle());
  1018. UnicodeString ProgressTitle = GetAppProgressTitle();
  1019. if (!ProgressTitle.IsEmpty())
  1020. {
  1021. NewTitle = ProgressTitle + TitleSeparator + NewTitle;
  1022. }
  1023. else if (ScpExplorer != NULL)
  1024. {
  1025. UnicodeString Path = ScpExplorer->PathForCaption();
  1026. if (!Path.IsEmpty())
  1027. {
  1028. NewTitle = Path + TitleSeparator + NewTitle;
  1029. }
  1030. }
  1031. // Not updating MainForm here, as for all other possible main forms, this code is actually not what we want.
  1032. // And they all update their title on their own (some using GetAppProgressTitle()).
  1033. ScpExplorer->Caption = NewTitle;
  1034. ScpExplorer->ApplicationTitleChanged();
  1035. }
  1036. }
  1037. //---------------------------------------------------------------------------
  1038. void __fastcall TTerminalManager::SaveTerminal(TTerminal * Terminal)
  1039. {
  1040. TSessionData * Data = StoredSessions->FindSame(Terminal->SessionData);
  1041. if (Data != NULL)
  1042. {
  1043. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  1044. DebugAssert(ManagedTerminal != NULL);
  1045. bool Changed = false;
  1046. if (Terminal->SessionData->UpdateDirectories)
  1047. {
  1048. Data->CopyDirectoriesStateData(ManagedTerminal->StateData);
  1049. Changed = true;
  1050. }
  1051. if (Changed)
  1052. {
  1053. // modified only, implicit
  1054. StoredSessions->Save(false, false);
  1055. }
  1056. }
  1057. }
  1058. //---------------------------------------------------------------------------
  1059. void __fastcall TTerminalManager::HandleException(Exception * E)
  1060. {
  1061. // can be null for example when exception is thrown on login dialog
  1062. if (ActiveTerminal != NULL)
  1063. {
  1064. ActiveTerminal->ShowExtendedException(E);
  1065. }
  1066. else
  1067. {
  1068. ShowExtendedException(E);
  1069. }
  1070. }
  1071. //---------------------------------------------------------------------------
  1072. void __fastcall TTerminalManager::ApplicationException(TObject * /*Sender*/,
  1073. Exception * E)
  1074. {
  1075. HandleException(E);
  1076. }
  1077. //---------------------------------------------------------------------------
  1078. void __fastcall TTerminalManager::ApplicationShowHint(UnicodeString & HintStr,
  1079. bool & /*CanShow*/, THintInfo & HintInfo)
  1080. {
  1081. HintInfo.HintData = HintInfo.HintControl;
  1082. if (HasLabelHintPopup(HintInfo.HintControl, HintStr))
  1083. {
  1084. // Hack for transfer setting labels.
  1085. // Should be converted to something like HintLabel()
  1086. HintInfo.HideTimeout = 100000; // "almost" never
  1087. }
  1088. else if (dynamic_cast<TProgressBar *>(HintInfo.HintControl) != NULL)
  1089. {
  1090. // Hint is forcibly hidden in TProgressForm::FormHide
  1091. HintInfo.HideTimeout = 100000; // "almost" never
  1092. HintInfo.ReshowTimeout = 500; // updated each 0.5s
  1093. }
  1094. else
  1095. {
  1096. int HintMaxWidth = 300;
  1097. TControl * ScaleControl = HintInfo.HintControl;
  1098. if (DebugAlwaysFalse(HintInfo.HintControl == NULL) ||
  1099. (GetParentForm(HintInfo.HintControl) == NULL))
  1100. {
  1101. ScaleControl = ScpExplorer;
  1102. }
  1103. HintMaxWidth = ScaleByTextHeight(ScaleControl, HintMaxWidth);
  1104. HintInfo.HintMaxWidth = HintMaxWidth;
  1105. }
  1106. }
  1107. //---------------------------------------------------------------------------
  1108. bool __fastcall TTerminalManager::HandleMouseWheel(WPARAM WParam, LPARAM LParam)
  1109. {
  1110. // WORKAROUND This is no longer necessary on Windows 10 (except for WM_WANTS_MOUSEWHEEL_INACTIVE part)
  1111. bool Result = false;
  1112. if (Application->Active)
  1113. {
  1114. TPoint Point(LOWORD(LParam), HIWORD(LParam));
  1115. TWinControl * Control = FindVCLWindow(Point);
  1116. if (Control != NULL)
  1117. {
  1118. TCustomForm * Form = GetParentForm(Control);
  1119. // Only case we expect the parent form to be NULL is on the Find/Replace dialog,
  1120. // which is owned by VCL's internal TRedirectorWindow.
  1121. DebugAssert((Form != NULL) || (Control->ClassName() == L"TRedirectorWindow"));
  1122. if (Form != NULL)
  1123. {
  1124. // Send it only to windows we tested it with.
  1125. // Though we should sooner or later remove this test and pass it to all our windows.
  1126. if (Form->Active && (Form->Perform(WM_WANTS_MOUSEWHEEL, 0, 0) == 1))
  1127. {
  1128. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  1129. Result = true;
  1130. }
  1131. else if (!Form->Active && (Form->Perform(WM_WANTS_MOUSEWHEEL_INACTIVE, 0, 0) == 1))
  1132. {
  1133. TWinControl * Control2;
  1134. // FindVCLWindow stops on window level, when the window is not active? or when there's a modal window over it?
  1135. // (but in any case, when we have operation running on top of Synchronization checklist).
  1136. // WORKAROUND: The while loop does what AllLevels parameter of ControlAtPos should do, but it's broken.
  1137. // Based on (now removed) Embarcadero QC 82143.
  1138. while ((Control2 = dynamic_cast<TWinControl *>(Control->ControlAtPos(Control->ScreenToClient(Point), false, true))) != NULL)
  1139. {
  1140. Control = Control2;
  1141. }
  1142. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  1143. Result = true;
  1144. }
  1145. }
  1146. }
  1147. }
  1148. return Result;
  1149. }
  1150. //---------------------------------------------------------------------------
  1151. void __fastcall TTerminalManager::ApplicationMessage(TMsg & Msg, bool & Handled)
  1152. {
  1153. if (Msg.message == FTaskbarButtonCreatedMessage)
  1154. {
  1155. CreateTaskbarList();
  1156. }
  1157. if (Msg.message == WM_MOUSEWHEEL)
  1158. {
  1159. Handled = HandleMouseWheel(Msg.wParam, Msg.lParam);
  1160. }
  1161. }
  1162. //---------------------------------------------------------------------------
  1163. void __fastcall TTerminalManager::ApplicationModalBegin(TObject * /*Sender*/)
  1164. {
  1165. InterfaceStartDontMeasure();
  1166. NonVisualDataModule->StartBusy();
  1167. if (ScpExplorer != NULL)
  1168. {
  1169. ScpExplorer->SuspendWindowLock();
  1170. }
  1171. }
  1172. //---------------------------------------------------------------------------
  1173. void __fastcall TTerminalManager::ApplicationModalEnd(TObject * /*Sender*/)
  1174. {
  1175. NonVisualDataModule->EndBusy();
  1176. if (ScpExplorer != NULL)
  1177. {
  1178. ScpExplorer->ResumeWindowLock();
  1179. }
  1180. }
  1181. //---------------------------------------------------------------------------
  1182. void __fastcall TTerminalManager::InitTaskbarButtonCreatedMessage()
  1183. {
  1184. // XE6 VCL already handles TaskbarButtonCreated, but does not call ChangeWindowMessageFilterEx.
  1185. // So we keep our implementation.
  1186. // See also https://stackoverflow.com/q/14614823/850848#14618587
  1187. FTaskbarButtonCreatedMessage = RegisterWindowMessage(L"TaskbarButtonCreated");
  1188. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  1189. ChangeWindowMessageFilterExProc ChangeWindowMessageFilterEx =
  1190. (ChangeWindowMessageFilterExProc)GetProcAddress(User32Library, "ChangeWindowMessageFilterEx");
  1191. if (ChangeWindowMessageFilterEx != NULL)
  1192. {
  1193. // without this we won't get TaskbarButtonCreated, when app is running elevated
  1194. ChangeWindowMessageFilterEx(
  1195. Application->Handle, FTaskbarButtonCreatedMessage, MSGFLT_ALLOW, NULL);
  1196. }
  1197. }
  1198. //---------------------------------------------------------------------------
  1199. void __fastcall TTerminalManager::CreateTaskbarList()
  1200. {
  1201. ReleaseTaskbarList();
  1202. if(SUCCEEDED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL,
  1203. IID_ITaskbarList3, (void **) &FTaskbarList)))
  1204. {
  1205. if (ScpExplorer != NULL)
  1206. {
  1207. UpdateTaskbarList();
  1208. }
  1209. }
  1210. }
  1211. //---------------------------------------------------------------------------
  1212. void __fastcall TTerminalManager::ReleaseTaskbarList()
  1213. {
  1214. if (FTaskbarList != NULL)
  1215. {
  1216. FTaskbarList->Release();
  1217. }
  1218. }
  1219. //---------------------------------------------------------------------------
  1220. void __fastcall TTerminalManager::UpdateTaskbarList()
  1221. {
  1222. ScpExplorer->UpdateTaskbarList(FTaskbarList);
  1223. }
  1224. //---------------------------------------------------------------------------
  1225. void __fastcall TTerminalManager::DeleteLocalFile(const UnicodeString FileName, bool Alternative, int & Deleted)
  1226. {
  1227. Deleted = RecursiveDeleteFileChecked(FileName, (WinConfiguration->DeleteToRecycleBin != Alternative));
  1228. }
  1229. //---------------------------------------------------------------------------
  1230. void __fastcall TTerminalManager::TerminalQueryUser(TObject * Sender,
  1231. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  1232. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * /*Arg*/)
  1233. {
  1234. TTerminal * Terminal = DebugNotNull(dynamic_cast<TTerminal *>(Sender));
  1235. UnicodeString HelpKeyword;
  1236. TMessageParams MessageParams(Params);
  1237. UnicodeString AQuery = Query;
  1238. if (Params != NULL)
  1239. {
  1240. HelpKeyword = Params->HelpKeyword;
  1241. if (FLAGSET(Params->Params, qpFatalAbort))
  1242. {
  1243. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  1244. if (!MessageParams.TimerMessage.IsEmpty())
  1245. {
  1246. MessageParams.TimerMessage = FMTLOAD(WARN_FATAL_ERROR, (MessageParams.TimerMessage));
  1247. }
  1248. }
  1249. }
  1250. if (ScpExplorer)
  1251. {
  1252. Answer = ScpExplorer->MoreMessageDialog(AQuery, MoreMessages, Type, Answers,
  1253. HelpKeyword, &MessageParams, Terminal);
  1254. }
  1255. else
  1256. {
  1257. Answer = MoreMessageDialog(AQuery, MoreMessages, Type, Answers, HelpKeyword,
  1258. &MessageParams);
  1259. }
  1260. }
  1261. //---------------------------------------------------------------------------
  1262. void __fastcall TTerminalManager::AuthenticateFormCancel(TObject * Sender)
  1263. {
  1264. TAuthenticateForm * Form = dynamic_cast<TAuthenticateForm *>(Sender);
  1265. DebugAssert(Form != NULL);
  1266. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Form->Terminal);
  1267. // will be null e.g. for background transfers
  1268. if (ManagedTerminal != NULL)
  1269. {
  1270. TTerminalThread * TerminalThread = ManagedTerminal->TerminalThread;
  1271. // can be NULL for reconnects from transfers
  1272. if ((TerminalThread != NULL) && !TerminalThread->Cancelling)
  1273. {
  1274. Form->Log(LoadStr(AUTH_CANCELLING));
  1275. TerminalThread->Cancel();
  1276. }
  1277. }
  1278. FAuthenticationCancelled = true;
  1279. }
  1280. //---------------------------------------------------------------------------
  1281. TAuthenticateForm * __fastcall TTerminalManager::MakeAuthenticateForm(
  1282. TTerminal * Terminal)
  1283. {
  1284. TAuthenticateForm * Dialog = SafeFormCreate<TAuthenticateForm>();
  1285. Dialog->Init(Terminal);
  1286. DebugAssert(Dialog->OnCancel == NULL);
  1287. Dialog->OnCancel = AuthenticateFormCancel;
  1288. return Dialog;
  1289. }
  1290. //---------------------------------------------------------------------------
  1291. void __fastcall TTerminalManager::FileNameInputDialogInitializeRenameBaseName(
  1292. TObject * /*Sender*/, TInputDialogData * Data)
  1293. {
  1294. EditSelectBaseName(Data->Edit->Handle);
  1295. }
  1296. //---------------------------------------------------------------------------
  1297. void __fastcall TTerminalManager::TerminalPromptUser(
  1298. TTerminal * Terminal, TPromptKind Kind, UnicodeString Name, UnicodeString Instructions,
  1299. TStrings * Prompts, TStrings * Results, bool & Result, void * /*Arg*/)
  1300. {
  1301. if (((Kind == pkPrompt) || (Kind == pkFileName)) && (FAuthenticateForm == NULL) &&
  1302. (Terminal->Status != ssOpening))
  1303. {
  1304. DebugAssert(Instructions.IsEmpty());
  1305. DebugAssert(Prompts->Count == 1);
  1306. DebugAssert(FLAGSET(int(Prompts->Objects[0]), pupEcho));
  1307. UnicodeString AResult = Results->Strings[0];
  1308. TInputDialogInitialize InputDialogInitialize = NULL;
  1309. if ((Kind == pkFileName) && !WinConfiguration->RenameWholeName)
  1310. {
  1311. InputDialogInitialize = FileNameInputDialogInitializeRenameBaseName;
  1312. }
  1313. Result = InputDialog(Name, Prompts->Strings[0], AResult, L"", NULL, false, InputDialogInitialize);
  1314. if (Result)
  1315. {
  1316. Results->Strings[0] = AResult;
  1317. }
  1318. }
  1319. else
  1320. {
  1321. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  1322. if (AuthenticateForm == NULL)
  1323. {
  1324. AuthenticateForm = MakeAuthenticateForm(Terminal);
  1325. }
  1326. try
  1327. {
  1328. Result = AuthenticateForm->PromptUser(Kind, Name, Instructions, Prompts, Results,
  1329. (FAuthenticateForm != NULL), Terminal->StoredCredentialsTried);
  1330. }
  1331. __finally
  1332. {
  1333. if (FAuthenticateForm == NULL)
  1334. {
  1335. delete AuthenticateForm;
  1336. }
  1337. }
  1338. }
  1339. }
  1340. //---------------------------------------------------------------------------
  1341. void __fastcall TTerminalManager::TerminalDisplayBanner(
  1342. TTerminal * Terminal, UnicodeString SessionName,
  1343. const UnicodeString & Banner, bool & NeverShowAgain, int Options, unsigned int & Params)
  1344. {
  1345. DebugAssert(FAuthenticateForm != NULL);
  1346. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  1347. if (AuthenticateForm == NULL)
  1348. {
  1349. AuthenticateForm = MakeAuthenticateForm(Terminal);
  1350. }
  1351. try
  1352. {
  1353. AuthenticateForm->Banner(Banner, NeverShowAgain, Options, Params);
  1354. }
  1355. __finally
  1356. {
  1357. if (FAuthenticateForm == NULL)
  1358. {
  1359. delete AuthenticateForm;
  1360. }
  1361. }
  1362. }
  1363. //---------------------------------------------------------------------------
  1364. void __fastcall TTerminalManager::TerminalShowExtendedException(
  1365. TTerminal * Terminal, Exception * E, void * /*Arg*/)
  1366. {
  1367. if (ScpExplorer)
  1368. {
  1369. ScpExplorer->ShowExtendedException(Terminal, E);
  1370. }
  1371. else
  1372. {
  1373. ShowExtendedExceptionEx(Terminal, E);
  1374. }
  1375. }
  1376. //---------------------------------------------------------------------------
  1377. static TDateTime DirectoryReadingProgressDelay(0, 0, 1, 500);
  1378. //---------------------------------------------------------------------------
  1379. void __fastcall TTerminalManager::TerminalReadDirectoryProgress(
  1380. TObject * Sender, int Progress, int ResolvedLinks, bool & Cancel)
  1381. {
  1382. DebugAlwaysTrue((Sender == FOpeningTerminal) == (FAuthenticateForm != NULL));
  1383. if (Progress == 0)
  1384. {
  1385. if ((ScpExplorer != NULL) && (Sender != FOpeningTerminal))
  1386. {
  1387. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  1388. ScpExplorer->LockWindow();
  1389. }
  1390. FDirectoryReadingStart = Now();
  1391. if (!FProgressTitle.IsEmpty() || !FForegroundProgressTitle.IsEmpty())
  1392. {
  1393. FProgressTitle = L"";
  1394. FForegroundProgressTitle = L"";
  1395. UpdateAppTitle();
  1396. }
  1397. // Reset "was ESC ever pressed?" state
  1398. GetAsyncKeyState(VK_ESCAPE);
  1399. }
  1400. else if (Progress < 0)
  1401. {
  1402. if (Progress == -2)
  1403. {
  1404. // cancelled
  1405. if (ScpExplorer != NULL)
  1406. {
  1407. ScpExplorer->ReadDirectoryCancelled();
  1408. }
  1409. }
  1410. else
  1411. {
  1412. if ((ScpExplorer != NULL) && (Sender != FOpeningTerminal))
  1413. {
  1414. ScpExplorer->UnlockWindow();
  1415. }
  1416. FProgressTitle = L"";
  1417. FForegroundProgressTitle = L"";
  1418. UpdateAppTitle();
  1419. }
  1420. }
  1421. else
  1422. {
  1423. // If the least significant bit is set,
  1424. // the key was pressed after the previous call to GetAsyncKeyState.
  1425. int KeyState = GetAsyncKeyState(VK_ESCAPE);
  1426. if (FLAGSET(KeyState, 0x01))
  1427. {
  1428. Cancel = true;
  1429. }
  1430. if ((Now() - FDirectoryReadingStart) >= DirectoryReadingProgressDelay)
  1431. {
  1432. // 4 is arbitrary number
  1433. FForegroundProgressTitle =
  1434. FMTLOAD(ResolvedLinks >= 4 ? DIRECTORY_READING_AND_RESOLVING_PROGRESS : DIRECTORY_READING_PROGRESS,
  1435. (Progress));
  1436. UpdateAppTitle();
  1437. }
  1438. }
  1439. }
  1440. //---------------------------------------------------------------------------
  1441. void __fastcall TTerminalManager::TerminalCustomCommand(
  1442. TTerminal * /*Terminal*/, const UnicodeString & Command, bool & Handled)
  1443. {
  1444. // Implementation has to be thread-safe
  1445. Handled = CopyCommandToClipboard(Command);
  1446. }
  1447. //---------------------------------------------------------------------------
  1448. void __fastcall TTerminalManager::AuthenticatingDone()
  1449. {
  1450. FAuthenticating--;
  1451. if (FAuthenticating == 0)
  1452. {
  1453. BusyEnd(FBusyToken);
  1454. FBusyToken = NULL;
  1455. }
  1456. if (!FKeepAuthenticateForm)
  1457. {
  1458. CloseAutheticateForm();
  1459. }
  1460. }
  1461. //---------------------------------------------------------------------------
  1462. void __fastcall TTerminalManager::TerminalInformation(
  1463. TTerminal * Terminal, const UnicodeString & Str, int Phase, const UnicodeString & Additional)
  1464. {
  1465. if (ScpExplorer != NULL)
  1466. {
  1467. ScpExplorer->TerminalConnecting();
  1468. }
  1469. if (Phase == 1)
  1470. {
  1471. if (FAuthenticating == 0)
  1472. {
  1473. FBusyToken = BusyStart();
  1474. }
  1475. FAuthenticating++;
  1476. }
  1477. else if (Phase == 0)
  1478. {
  1479. DebugAssert(FAuthenticating > 0);
  1480. AuthenticatingDone();
  1481. }
  1482. else
  1483. {
  1484. if (FAuthenticating > 0)
  1485. {
  1486. bool ShowPending = false;
  1487. if (FAuthenticateForm == NULL)
  1488. {
  1489. FAuthenticateForm = MakeAuthenticateForm(Terminal);
  1490. ShowPending = true;
  1491. }
  1492. FAuthenticateForm->Log(Str, Additional);
  1493. if (ShowPending)
  1494. {
  1495. FAuthenticateForm->ShowAsModal();
  1496. }
  1497. }
  1498. }
  1499. }
  1500. //---------------------------------------------------------------------------
  1501. void __fastcall TTerminalManager::OperationFinished(::TFileOperation Operation,
  1502. TOperationSide Side, bool Temp, const UnicodeString & FileName, bool Success, bool NotCancelled,
  1503. TOnceDoneOperation & OnceDoneOperation)
  1504. {
  1505. DebugAssert(ScpExplorer);
  1506. ScpExplorer->OperationFinished(Operation, Side, Temp, FileName, Success, NotCancelled, OnceDoneOperation);
  1507. }
  1508. //---------------------------------------------------------------------------
  1509. void __fastcall TTerminalManager::OperationProgress(
  1510. TFileOperationProgressType & ProgressData)
  1511. {
  1512. UpdateAppTitle();
  1513. DebugAssert(ScpExplorer);
  1514. ScpExplorer->OperationProgress(ProgressData);
  1515. }
  1516. //---------------------------------------------------------------------------
  1517. void __fastcall TTerminalManager::QueueEvent(TTerminalQueue * Queue, TQueueEvent Event)
  1518. {
  1519. TGuard Guard(FQueueSection);
  1520. FQueueEvents.push_back(std::make_pair(Queue, Event));
  1521. }
  1522. //---------------------------------------------------------------------------
  1523. void __fastcall TTerminalManager::DoConfigurationChange()
  1524. {
  1525. DebugAssert(Configuration);
  1526. DebugAssert(Configuration == WinConfiguration);
  1527. TTerminalQueue * Queue;
  1528. for (int Index = 0; Index < Count; Index++)
  1529. {
  1530. DebugAssert(Sessions[Index]->Log);
  1531. Sessions[Index]->Log->ReflectSettings();
  1532. Sessions[Index]->ActionLog->ReflectSettings();
  1533. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1534. SetQueueConfiguration(Queue);
  1535. }
  1536. if (ScpExplorer)
  1537. {
  1538. ScpExplorer->ConfigurationChanged();
  1539. }
  1540. }
  1541. //---------------------------------------------------------------------------
  1542. void __fastcall TTerminalManager::ConfigurationChange(TObject * /*Sender*/)
  1543. {
  1544. if (FMainThread == GetCurrentThreadId())
  1545. {
  1546. DoConfigurationChange();
  1547. }
  1548. else
  1549. {
  1550. TGuard Guard(FChangeSection.get());
  1551. FPendingConfigurationChange++;
  1552. }
  1553. }
  1554. //---------------------------------------------------------------------------
  1555. void __fastcall TTerminalManager::SessionReady()
  1556. {
  1557. UpdateScpExplorer();
  1558. ScpExplorer->SessionReady();
  1559. }
  1560. //---------------------------------------------------------------------------
  1561. TStrings * __fastcall TTerminalManager::GetSessionList()
  1562. {
  1563. FSessionList->Clear();
  1564. for (int i = 0; i < Count; i++)
  1565. {
  1566. TManagedTerminal * Terminal = Sessions[i];
  1567. UnicodeString Name = GetSessionTitle(Terminal, true);
  1568. FSessionList->AddObject(Name, Terminal);
  1569. }
  1570. return FSessionList;
  1571. }
  1572. //---------------------------------------------------------------------------
  1573. int __fastcall TTerminalManager::GetActiveSessionIndex()
  1574. {
  1575. return (ActiveSession != NULL) ? IndexOf(ActiveSession) : -1;
  1576. }
  1577. //---------------------------------------------------------------------------
  1578. void __fastcall TTerminalManager::SetActiveSessionIndex(int value)
  1579. {
  1580. ActiveSession = Sessions[value];
  1581. }
  1582. //---------------------------------------------------------------------------
  1583. UnicodeString TTerminalManager::GetPathForSessionTabName(const UnicodeString & Path)
  1584. {
  1585. UnicodeString Result = Path;
  1586. const int MaxPathLen = 16;
  1587. if ((WinConfiguration->SessionTabNameFormat == stnfShortPathTrunc) &&
  1588. (Result.Length() > MaxPathLen))
  1589. {
  1590. Result = Result.SubString(1, MaxPathLen - 2) + Ellipsis;
  1591. }
  1592. return Result;
  1593. }
  1594. //---------------------------------------------------------------------------
  1595. UnicodeString __fastcall TTerminalManager::GetSessionTitle(TManagedTerminal * Session, bool Unique)
  1596. {
  1597. UnicodeString Result;
  1598. if (!Session->LocalBrowser)
  1599. {
  1600. Result = Session->SessionData->SessionName;
  1601. if (Unique &&
  1602. (WinConfiguration->SessionTabNameFormat != stnfNone))
  1603. {
  1604. int Index = IndexOf(Session);
  1605. // not for background transfer sessions and disconnected sessions
  1606. if ((Index >= 0) && Session->Active)
  1607. {
  1608. for (int Index2 = 0; Index2 < Count; Index2++)
  1609. {
  1610. UnicodeString Name = Sessions[Index2]->SessionData->SessionName;
  1611. if ((Sessions[Index2] != Session) &&
  1612. Sessions[Index2]->Active &&
  1613. SameText(Name, Result))
  1614. {
  1615. UnicodeString Path = ExtractShortName(Session->CurrentDirectory, true);
  1616. if (!Path.IsEmpty())
  1617. {
  1618. Path = GetPathForSessionTabName(Path);
  1619. Result = FORMAT(L"%s (%s)", (Result, Path));
  1620. }
  1621. break;
  1622. }
  1623. }
  1624. }
  1625. }
  1626. }
  1627. else
  1628. {
  1629. // should happen only when closing
  1630. if (ScpExplorer != NULL)
  1631. {
  1632. Result = ScpExplorer->GetLocalBrowserSessionTitle(Session);
  1633. }
  1634. }
  1635. return Result;
  1636. }
  1637. //---------------------------------------------------------------------------
  1638. UnicodeString TTerminalManager::FormatTerminalNoteMessage(TManagedTerminal * Terminal, const UnicodeString & Message)
  1639. {
  1640. return FORMAT(L"%s: %s", (GetSessionTitle(Terminal, true), Message));
  1641. }
  1642. //---------------------------------------------------------------------------
  1643. UnicodeString __fastcall TTerminalManager::GetActiveSessionAppTitle()
  1644. {
  1645. UnicodeString Result;
  1646. if ((ActiveSession != NULL) && !ActiveSession->LocalBrowser)
  1647. {
  1648. Result = GetSessionTitle(ActiveSession, false);
  1649. }
  1650. return Result;
  1651. }
  1652. //---------------------------------------------------------------------------
  1653. TTerminalQueue * __fastcall TTerminalManager::GetActiveQueue()
  1654. {
  1655. TTerminalQueue * Result = NULL;
  1656. if (ActiveSession != NULL)
  1657. {
  1658. Result = reinterpret_cast<TTerminalQueue *>(FQueues->Items[ActiveSessionIndex]);
  1659. }
  1660. return Result;
  1661. }
  1662. //---------------------------------------------------------------------------
  1663. void __fastcall TTerminalManager::CycleTerminals(bool Forward)
  1664. {
  1665. if (Count > 0)
  1666. {
  1667. int Index = ActiveSessionIndex;
  1668. Index += Forward ? 1 : -1;
  1669. if (Index < 0)
  1670. {
  1671. Index = Count-1;
  1672. }
  1673. else if (Index >= Count)
  1674. {
  1675. Index = 0;
  1676. }
  1677. ActiveSessionIndex = Index;
  1678. }
  1679. }
  1680. //---------------------------------------------------------------------------
  1681. bool __fastcall TTerminalManager::CanOpenInPutty()
  1682. {
  1683. return (ActiveTerminal != NULL) && !GUIConfiguration->PuttyPath.Trim().IsEmpty();
  1684. }
  1685. //---------------------------------------------------------------------------
  1686. void __fastcall TTerminalManager::OpenInPutty()
  1687. {
  1688. Configuration->Usage->Inc(L"OpenInPutty");
  1689. TSessionData * Data = NULL;
  1690. try
  1691. {
  1692. // Is NULL on the first session when called from ConnectActiveTerminal()
  1693. // due to WinConfiguration->AutoOpenInPutty
  1694. if (ScpExplorer != NULL)
  1695. {
  1696. Data = ScpExplorer->CloneCurrentSessionData();
  1697. }
  1698. else
  1699. {
  1700. Data = new TSessionData(L"");
  1701. DebugAssert(ActiveTerminal != NULL);
  1702. Data->Assign(ActiveTerminal->SessionData);
  1703. ActiveTerminal->UpdateSessionCredentials(Data);
  1704. }
  1705. if (ActiveTerminal->TunnelLocalPortNumber != 0)
  1706. {
  1707. Data->ConfigureTunnel(ActiveTerminal->TunnelLocalPortNumber);
  1708. }
  1709. OpenSessionInPutty(Data);
  1710. }
  1711. __finally
  1712. {
  1713. delete Data;
  1714. }
  1715. }
  1716. //---------------------------------------------------------------------------
  1717. void __fastcall TTerminalManager::NewSession(
  1718. const UnicodeString & SessionUrl, bool ReloadSessions, TForm * LinkedForm, bool ReplaceExisting)
  1719. {
  1720. if (ReloadSessions)
  1721. {
  1722. StoredSessions->Reload();
  1723. }
  1724. std::unique_ptr<TObjectList> DataList;
  1725. bool Retry;
  1726. do
  1727. {
  1728. Retry = false;
  1729. if (!DataList) // first round
  1730. {
  1731. DataList.reset(new TObjectList());
  1732. UnicodeString DownloadFile; // unused
  1733. GetLoginData(SessionUrl, NULL, DataList.get(), DownloadFile, true, LinkedForm);
  1734. }
  1735. else
  1736. {
  1737. if (!DoLoginDialog(DataList.get(), LinkedForm))
  1738. {
  1739. Abort(); // As GetLoginData would do
  1740. }
  1741. }
  1742. if (DataList->Count > 0)
  1743. {
  1744. if (ReplaceExisting)
  1745. {
  1746. // Tested for only the implicit Commanders' local browser
  1747. DebugAssert((Count == 0) || ((Count == 1) && Sessions[0]->LocalBrowser));
  1748. TAutoNestingCounter UpdatingCounter(FUpdating); // prevent tab flicker
  1749. FreeAll();
  1750. }
  1751. TManagedTerminal * ANewSession = NewSessions(DataList.get());
  1752. bool AdHoc = (DataList->Count == 1) && (StoredSessions->FindSame(reinterpret_cast<TSessionData *>(DataList->Items[0])) == NULL);
  1753. bool CanRetry = SessionUrl.IsEmpty() && AdHoc;
  1754. bool ShowLoginWhenNoSession = WinConfiguration->ShowLoginWhenNoSession;
  1755. if (CanRetry)
  1756. {
  1757. // we will show our own login dialog, so prevent opening an empty one
  1758. WinConfiguration->ShowLoginWhenNoSession = false;
  1759. }
  1760. try
  1761. {
  1762. ActiveSession = ANewSession;
  1763. }
  1764. __finally
  1765. {
  1766. if (CanRetry) // do not reset the value, unless really needed, as it can theoretically be changed meanwhile by the user
  1767. {
  1768. WinConfiguration->ShowLoginWhenNoSession = ShowLoginWhenNoSession;
  1769. }
  1770. }
  1771. Retry = CanRetry && (ActiveSession != ANewSession);
  1772. }
  1773. }
  1774. while (Retry);
  1775. }
  1776. //---------------------------------------------------------------------------
  1777. void TTerminalManager::StartInactiveTerminalReconnect(TManagedTerminal * Terminal)
  1778. {
  1779. ReconnectingTerminal(Terminal);
  1780. Terminal->NextInactiveReconnect = TDateTime(); // just in case
  1781. FReconnectingInactiveTerminal = Terminal;
  1782. DebugAssert(Terminal->TerminalThread == NULL);
  1783. TTerminalThread * TerminalThread = CreateTerminalThread(Terminal);
  1784. Terminal->TerminalThread = TerminalThread;
  1785. TerminalThread->AllowAbandon = true;
  1786. TerminalThread->StartTerminalReopenNonInteractive();
  1787. FReconnectingNote = FormatTerminalNoteMessage(Terminal, LoadStr(SESSION_RECONNECTING));
  1788. ScpExplorer->PostNote(FReconnectingNote);
  1789. }
  1790. //---------------------------------------------------------------------------
  1791. void TTerminalManager::CheckInactiveTerminalReconnect()
  1792. {
  1793. TManagedTerminal * Terminal = DebugNotNull(FReconnectingInactiveTerminal);
  1794. TTerminalThread * TerminalThread = DebugNotNull(Terminal->TerminalThread);
  1795. TTerminalReopenResult ReopenResult = TerminalThread->IsTerminalReopenComplete();
  1796. UnicodeString SessionName = Terminal->SessionData->SessionName;
  1797. if (ReopenResult == trrPending)
  1798. {
  1799. AppLog(FORMAT(L"Inactive session %s is still being reconnected", (SessionName)));
  1800. }
  1801. else
  1802. {
  1803. try
  1804. {
  1805. DebugCheck(TerminalThread->Release());
  1806. }
  1807. __finally
  1808. {
  1809. ReconnectedTerminal(Terminal);
  1810. Terminal->TerminalThread = NULL;
  1811. FReconnectingInactiveTerminal = NULL;
  1812. }
  1813. if (ReopenResult == trrSucceeded)
  1814. {
  1815. AppLog(FORMAT(L"Inactive session %s was reconnected", (SessionName)));
  1816. ScpExplorer->CancelNote(FReconnectingNote);
  1817. ScpExplorer->InactiveTerminalNotify(Terminal, LoadStr(SESSION_RECONNECTED), qtInformation);
  1818. }
  1819. else
  1820. {
  1821. if (ReopenResult == trrFailed)
  1822. {
  1823. // in case it was disabled meanwhile
  1824. if (GUIConfiguration->SessionReopenAutoInactive)
  1825. {
  1826. int Interval = 2 * GUIConfiguration->SessionReopenAutoIdle;
  1827. AppLog(FORMAT(L"Inactive session %s failed to reconnect, will try again in %d ms", (SessionName, Interval)));
  1828. // Might want to consider SessionReopenTimeout
  1829. Terminal->NextInactiveReconnect = IncMilliSecond(Now(), Interval);
  1830. }
  1831. else
  1832. {
  1833. Terminal->NextInactiveReconnect = TDateTime();
  1834. }
  1835. }
  1836. else if (ReopenResult == trrNeedsInteraction)
  1837. {
  1838. AppLog(FORMAT(L"Inactive session %s needs interaction", (SessionName)));
  1839. ScpExplorer->CancelNote(FReconnectingNote);
  1840. ScpExplorer->InactiveTerminalNotify(Terminal, LoadStr(SESSION_NEED_INTERACTION), qtInformation);
  1841. Terminal->NextInactiveReconnect = TDateTime();
  1842. }
  1843. try
  1844. {
  1845. if (Terminal->Active)
  1846. {
  1847. Terminal->Close();
  1848. }
  1849. }
  1850. catch (...)
  1851. {
  1852. }
  1853. }
  1854. FReconnectingNote = EmptyStr;
  1855. }
  1856. }
  1857. //---------------------------------------------------------------------------
  1858. void __fastcall TTerminalManager::Idle(bool SkipCurrentTerminal)
  1859. {
  1860. if (FPendingConfigurationChange > 0) // optimization
  1861. {
  1862. bool Changed = false;
  1863. {
  1864. TGuard Guard(FChangeSection.get());
  1865. if (DebugAlwaysTrue(FPendingConfigurationChange > 0))
  1866. {
  1867. FPendingConfigurationChange--;
  1868. Changed = true;
  1869. }
  1870. }
  1871. if (Changed)
  1872. {
  1873. DoConfigurationChange();
  1874. }
  1875. }
  1876. for (int Index = 0; Index < Count; Index++)
  1877. {
  1878. TManagedTerminal * Terminal = Sessions[Index];
  1879. try
  1880. {
  1881. if (Terminal == FReconnectingInactiveTerminal)
  1882. {
  1883. CheckInactiveTerminalReconnect();
  1884. }
  1885. else if (!SkipCurrentTerminal || (Terminal != ActiveTerminal))
  1886. {
  1887. // make sure Idle is called on the thread that runs the terminal
  1888. if (Terminal->TerminalThread != NULL)
  1889. {
  1890. Terminal->TerminalThread->Idle();
  1891. }
  1892. else
  1893. {
  1894. if (Terminal->Active)
  1895. {
  1896. Terminal->Idle();
  1897. }
  1898. else if ((Terminal != ActiveTerminal) &&
  1899. GUIConfiguration->SessionReopenAutoInactive &&
  1900. (FReconnectingInactiveTerminal == NULL) &&
  1901. (Terminal->NextInactiveReconnect != TDateTime()) &&
  1902. (Terminal->NextInactiveReconnect < Now()))
  1903. {
  1904. StartInactiveTerminalReconnect(Terminal);
  1905. }
  1906. }
  1907. if (Terminal->Active)
  1908. {
  1909. DebugAssert(Index < FQueues->Count);
  1910. if (Index < FQueues->Count)
  1911. {
  1912. reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index])->Idle();
  1913. }
  1914. }
  1915. }
  1916. }
  1917. catch(Exception & E)
  1918. {
  1919. if (Terminal == ActiveTerminal)
  1920. {
  1921. // throw further, so that the exception is handled in proper place
  1922. // (particularly in broken-transfer reconnect handler, bug 72)
  1923. throw;
  1924. }
  1925. else
  1926. {
  1927. // we may not have inactive terminal, unless there is a explorer,
  1928. // also Idle is called from explorer anyway
  1929. if (DebugAlwaysTrue(ScpExplorer != NULL))
  1930. {
  1931. ScpExplorer->InactiveTerminalNotify(Terminal, EmptyStr, qtError, &E);
  1932. }
  1933. if (!Terminal->Active)
  1934. {
  1935. // if session is lost, save the error message and rethrow it
  1936. // once the terminal gets activated
  1937. Terminal->InactiveTerminationMessage = E.Message;
  1938. Terminal->NextInactiveReconnect = IncMilliSecond(Now(), GUIConfiguration->SessionReopenAutoIdle);
  1939. }
  1940. }
  1941. }
  1942. }
  1943. TTerminalQueue * QueueWithEvent;
  1944. TQueueEvent QueueEvent;
  1945. do
  1946. {
  1947. QueueWithEvent = NULL;
  1948. {
  1949. TGuard Guard(FQueueSection);
  1950. if (!FQueueEvents.empty())
  1951. {
  1952. QueueWithEvent = FQueueEvents[0].first;
  1953. QueueEvent = FQueueEvents[0].second;
  1954. FQueueEvents.erase(FQueueEvents.begin());
  1955. }
  1956. }
  1957. if (QueueWithEvent != NULL)
  1958. {
  1959. int Index = FQueues->IndexOf(QueueWithEvent);
  1960. // the session may not exist anymore
  1961. if (Index >= 0)
  1962. {
  1963. TManagedTerminal * Terminal = Sessions[Index];
  1964. // we can hardly have a queue event without explorer
  1965. DebugAssert(ScpExplorer != NULL);
  1966. if (ScpExplorer != NULL)
  1967. {
  1968. ScpExplorer->QueueEvent(Terminal, QueueWithEvent, QueueEvent);
  1969. }
  1970. }
  1971. }
  1972. }
  1973. while (QueueWithEvent != NULL);
  1974. }
  1975. //---------------------------------------------------------------------------
  1976. void __fastcall TTerminalManager::MasterPasswordPrompt()
  1977. {
  1978. if (GetCurrentThreadId() == MainThreadID)
  1979. {
  1980. if (!DoMasterPasswordDialog())
  1981. {
  1982. Abort();
  1983. }
  1984. }
  1985. else
  1986. {
  1987. // this can happen only when we keep cancelling all master password prompts
  1988. // as long as the sessing finally connects (session password has to be
  1989. // explictly typed in), and background transfer is started
  1990. Abort();
  1991. }
  1992. }
  1993. //---------------------------------------------------------------------------
  1994. void __fastcall TTerminalManager::Move(TTerminal * Source, TTerminal * Target)
  1995. {
  1996. int SourceIndex = IndexOf(Source);
  1997. int TargetIndex = IndexOf(Target);
  1998. TTerminalList::Move(SourceIndex, TargetIndex);
  1999. FQueues->Move(SourceIndex, TargetIndex);
  2000. DoSessionListChanged();
  2001. // when there are indexed sessions with the same name,
  2002. // the index may change when reordering the sessions
  2003. UpdateAppTitle();
  2004. }
  2005. //---------------------------------------------------------------------------
  2006. void __fastcall TTerminalManager::DoSessionListChanged()
  2007. {
  2008. if ((FScpExplorer != NULL) && !Updating)
  2009. {
  2010. FScpExplorer->SessionListChanged();
  2011. }
  2012. }
  2013. //---------------------------------------------------------------------------
  2014. void __fastcall TTerminalManager::SaveWorkspace(TList * DataList)
  2015. {
  2016. for (int Index = 0; Index < Count; Index++)
  2017. {
  2018. TManagedTerminal * ManagedTerminal = Sessions[Index];
  2019. TSessionData * Data = StoredSessions->SaveWorkspaceData(ManagedTerminal->StateData, Index);
  2020. if (ManagedTerminal->Active)
  2021. {
  2022. ManagedTerminal->UpdateSessionCredentials(Data);
  2023. }
  2024. DataList->Add(Data);
  2025. }
  2026. }
  2027. //---------------------------------------------------------------------------
  2028. bool TTerminalManager::IsAvailableTerminal(TTerminal * Terminal)
  2029. {
  2030. return
  2031. (Terminal != NULL) &&
  2032. Terminal->Active &&
  2033. !IsReconnectingTerminal(Terminal);
  2034. }
  2035. //---------------------------------------------------------------------------
  2036. bool TTerminalManager::IsReconnectingTerminal(TTerminal * Terminal)
  2037. {
  2038. return
  2039. (Terminal != NULL) &&
  2040. ((Terminal == FOpeningTerminal) || (Terminal == FReconnectingInactiveTerminal));
  2041. }
  2042. //---------------------------------------------------------------------------
  2043. bool TTerminalManager::IsAvailableTerminalForSite(TTerminal * Terminal, TSessionData * Data)
  2044. {
  2045. bool Result = IsAvailableTerminal(Terminal);
  2046. if (Result)
  2047. {
  2048. std::unique_ptr<TSessionData> TerminalData(Terminal->SessionData->Clone());
  2049. Terminal->UpdateSessionCredentials(TerminalData.get());
  2050. Result = TerminalData->IsSameSite(Data);
  2051. }
  2052. return Result;
  2053. }
  2054. //---------------------------------------------------------------------------
  2055. TManagedTerminal * __fastcall TTerminalManager::FindActiveTerminalForSite(TSessionData * Data)
  2056. {
  2057. TManagedTerminal * Result = NULL;
  2058. for (int Index = 0; (Result == NULL) && (Index < Count); Index++)
  2059. {
  2060. TManagedTerminal * Terminal = Sessions[Index];
  2061. if (IsAvailableTerminalForSite(Terminal, Data))
  2062. {
  2063. Result = Terminal;
  2064. }
  2065. }
  2066. return Result;
  2067. }
  2068. //---------------------------------------------------------------------------
  2069. TTerminalQueue * __fastcall TTerminalManager::FindQueueForTerminal(TTerminal * Terminal)
  2070. {
  2071. int Index = IndexOf(Terminal);
  2072. return reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  2073. }
  2074. //---------------------------------------------------------------------------
  2075. bool __fastcall TTerminalManager::UploadPublicKey(
  2076. TTerminal * Terminal, TSessionData * Data, UnicodeString & FileName)
  2077. {
  2078. std::unique_ptr<TOpenDialog> OpenDialog(new TOpenDialog(Application));
  2079. OpenDialog->Title = LoadStr(LOGIN_PUBLIC_KEY_TITLE);
  2080. OpenDialog->Filter = LoadStr(LOGIN_PUBLIC_KEY_FILTER);
  2081. OpenDialog->DefaultExt = PuttyKeyExt;
  2082. OpenDialog->FileName = FileName;
  2083. bool Result = OpenDialog->Execute();
  2084. if (Result)
  2085. {
  2086. Configuration->Usage->Inc(L"PublicKeyInstallation");
  2087. FileName = OpenDialog->FileName;
  2088. VerifyAndConvertKey(FileName, false);
  2089. bool AdHocTerminal = (Terminal == NULL);
  2090. std::unique_ptr<TTerminal> TerminalOwner;
  2091. if (AdHocTerminal)
  2092. {
  2093. DebugAssert(Data != NULL);
  2094. TAutoFlag KeepAuthenticateFormFlag(FKeepAuthenticateForm);
  2095. try
  2096. {
  2097. TerminalOwner.reset(CreateTerminal(Data));
  2098. Terminal = TerminalOwner.get();
  2099. SetupTerminal(Terminal);
  2100. Terminal->OnProgress = NULL;
  2101. Terminal->OnFinished = NULL;
  2102. DoConnectTerminal(Terminal, false, true);
  2103. }
  2104. catch (Exception & E)
  2105. {
  2106. CloseAutheticateForm();
  2107. throw;
  2108. }
  2109. }
  2110. UnicodeString Installed;
  2111. try
  2112. {
  2113. UnicodeString SshImplementation = Terminal->GetSessionInfo().SshImplementation;
  2114. UnicodeString NotOpenSSHMessage = FMTLOAD(LOGIN_NOT_OPENSSH, (SshImplementation));
  2115. if (IsOpenSSH(SshImplementation) ||
  2116. (MessageDialog(NotOpenSSHMessage, qtConfirmation, qaOK | qaCancel, HELP_LOGIN_AUTHORIZED_KEYS) == qaOK))
  2117. {
  2118. // Ad-hoc terminal
  2119. if (FAuthenticateForm != NULL)
  2120. {
  2121. UnicodeString Comment;
  2122. bool UnusedHasCertificate;
  2123. GetPublicKeyLine(FileName, Comment, UnusedHasCertificate);
  2124. FAuthenticateForm->Log(FMTLOAD(LOGIN_PUBLIC_KEY_UPLOAD, (Comment)));
  2125. }
  2126. Installed = Terminal->UploadPublicKey(FileName);
  2127. }
  2128. }
  2129. __finally
  2130. {
  2131. CloseAutheticateForm(); // When uploading from Login dialog
  2132. }
  2133. if (!Installed.IsEmpty())
  2134. {
  2135. Terminal->LogEvent(L"Public key installation done.");
  2136. if (AdHocTerminal)
  2137. {
  2138. TerminalOwner.reset(NULL);
  2139. }
  2140. else
  2141. {
  2142. Terminal->Log->AddSeparator();
  2143. }
  2144. MessageDialog(Installed, qtInformation, qaOK, HELP_LOGIN_AUTHORIZED_KEYS);
  2145. }
  2146. }
  2147. return Result;
  2148. }
  2149. //---------------------------------------------------------------------------
  2150. bool TTerminalManager::IsUpdating()
  2151. {
  2152. return (FUpdating > 0);
  2153. }
  2154. //---------------------------------------------------------------------------
  2155. bool TTerminalManager::HookFatalExceptionMessageDialog(TMessageParams & Params)
  2156. {
  2157. bool Result =
  2158. DebugAlwaysTrue(ActiveTerminal != NULL) &&
  2159. DebugAlwaysTrue(Params.Timer == 0) &&
  2160. DebugAlwaysTrue(Params.TimerEvent == NULL) &&
  2161. DebugAlwaysTrue(FTerminalWithFatalExceptionTimer == NULL);
  2162. if (Result)
  2163. {
  2164. Params.Timer = MSecsPerSec / 4;
  2165. Params.TimerEvent = TerminalFatalExceptionTimer;
  2166. FTerminalWithFatalExceptionTimer = ActiveTerminal;
  2167. FTerminalReconnnecteScheduled = false;
  2168. }
  2169. return Result;
  2170. }
  2171. //---------------------------------------------------------------------------
  2172. void TTerminalManager::UnhookFatalExceptionMessageDialog()
  2173. {
  2174. DebugAssert(FTerminalWithFatalExceptionTimer != NULL);
  2175. FTerminalWithFatalExceptionTimer = NULL;
  2176. }
  2177. //---------------------------------------------------------------------------
  2178. bool TTerminalManager::ScheduleTerminalReconnnect(TTerminal * Terminal)
  2179. {
  2180. bool Result = (FTerminalWithFatalExceptionTimer == Terminal);
  2181. if (Result)
  2182. {
  2183. FTerminalReconnnecteScheduled = true;
  2184. }
  2185. return Result;
  2186. }
  2187. //---------------------------------------------------------------------------
  2188. void __fastcall TTerminalManager::TerminalFatalExceptionTimer(unsigned int & Result)
  2189. {
  2190. if (FTerminalReconnnecteScheduled)
  2191. {
  2192. Result = qaRetry;
  2193. FTerminalReconnnecteScheduled = false;
  2194. }
  2195. }
  2196. //---------------------------------------------------------------------------
  2197. TBitmap * TTerminalManager::ThumbnailNeeded(TManagedTerminal * Terminal, int Index, TRemoteFile * File, const TSize & Size)
  2198. {
  2199. TGuard Guard(Terminal->ThumbnailsSection.get());
  2200. TRemoteThumbnailsMap::iterator I = Terminal->Thumbnails.find(Index);
  2201. TBitmap * Result;
  2202. if ((I != Terminal->Thumbnails.end()) &&
  2203. UnixSamePath(File->FileName, I->second.FileName) &&
  2204. (I->second.ThumbnailSize == Size))
  2205. {
  2206. Result = I->second.Thumbnail;
  2207. }
  2208. else
  2209. {
  2210. TRemoteThumbnailNeeded ThumbnailNeeded;
  2211. ThumbnailNeeded.Index = Index;
  2212. ThumbnailNeeded.File = File->Duplicate();
  2213. ThumbnailNeeded.ThumbnailSize = Size;
  2214. Terminal->ThumbnailsQueue.push_back(ThumbnailNeeded);
  2215. if (I != Terminal->Thumbnails.end())
  2216. {
  2217. delete I->second.Thumbnail;
  2218. }
  2219. // Prevent duplicates in queue
  2220. TRemoteThumbnailData ThumbnailData;
  2221. ThumbnailData.FileName = File->FileName;
  2222. ThumbnailData.Thumbnail = NULL;
  2223. ThumbnailData.ThumbnailSize = Size;
  2224. Terminal->Thumbnails.insert(std::make_pair(Index, ThumbnailData));
  2225. if (Terminal->ThumbnailsEnabled)
  2226. {
  2227. NeedThumbnailDownloadQueueItem(Terminal);
  2228. }
  2229. Result = NULL;
  2230. }
  2231. return Result;
  2232. }
  2233. //---------------------------------------------------------------------------
  2234. void TTerminalManager::NeedThumbnailDownloadQueueItem(TManagedTerminal * ATerminal)
  2235. {
  2236. // Expects that ThumbnailsSection is already locked
  2237. if (ATerminal->ThumbnailDownloadQueueItem == NULL)
  2238. {
  2239. ATerminal->ThumbnailDownloadQueueItem = ScpExplorer->AddThumbnailDownloadQueueItem(ATerminal);
  2240. }
  2241. }
  2242. //---------------------------------------------------------------------------
  2243. void TTerminalManager::TerminalLoadedDirectory(TManagedTerminal * ATerminal)
  2244. {
  2245. DebugAssert(ActiveTerminal == ATerminal);
  2246. TGuard Guard(ATerminal->ThumbnailsSection.get());
  2247. AppLog(L"Loaded directory");
  2248. ATerminal->ThumbnailsEnabled = true;
  2249. if (!ATerminal->ThumbnailsQueue.empty())
  2250. {
  2251. NeedThumbnailDownloadQueueItem(ATerminal);
  2252. }
  2253. }
  2254. //---------------------------------------------------------------------------
  2255. //---------------------------------------------------------------------------
  2256. TThumbnailDownloadQueueItem::TThumbnailDownloadQueueItem(
  2257. TCustomScpExplorerForm * ScpExplorer, TManagedTerminal * Terminal, const UnicodeString & SourceDir,
  2258. const UnicodeString & TargetDir, const TCopyParamType * CopyParam) :
  2259. TTransferQueueItem(Terminal, NULL, TargetDir, CopyParam, cpNoConfirmation | cpTemporary, osRemote, true, false),
  2260. FScpExplorer(ScpExplorer), FManagedTerminal(Terminal)
  2261. {
  2262. FInfo->Source = SourceDir;
  2263. }
  2264. //---------------------------------------------------------------------------
  2265. __fastcall TThumbnailDownloadQueueItem::~TThumbnailDownloadQueueItem()
  2266. {
  2267. RecursiveDeleteFile(ExcludeTrailingBackslash(FTargetDir));
  2268. }
  2269. //---------------------------------------------------------------------------
  2270. bool TThumbnailDownloadQueueItem::Continue()
  2271. {
  2272. return !IsExecutionCancelled() && FManagedTerminal->ThumbnailsEnabled;
  2273. }
  2274. //---------------------------------------------------------------------------
  2275. bool TThumbnailDownloadQueueItem::CheckQueueFront(int Index, const UnicodeString & FileName, TSize ThumbnailSize)
  2276. {
  2277. TRemoteThumbnailsQueue & ThumbnailsQueue = FManagedTerminal->ThumbnailsQueue;
  2278. bool Result = !ThumbnailsQueue.empty();
  2279. if (Result)
  2280. {
  2281. const TRemoteThumbnailNeeded & ThumbnailNeeded = ThumbnailsQueue.front();
  2282. Result =
  2283. (ThumbnailNeeded.Index == Index) &&
  2284. (ThumbnailNeeded.File->FullFileName == FileName) &&
  2285. (ThumbnailNeeded.ThumbnailSize == ThumbnailSize);
  2286. }
  2287. return Result;
  2288. }
  2289. //---------------------------------------------------------------------------
  2290. void __fastcall TThumbnailDownloadQueueItem::DoTransferExecute(TTerminal * Terminal, TParallelOperation *)
  2291. {
  2292. TCriticalSection * Section = FManagedTerminal->ThumbnailsSection.get();
  2293. TGuard Guard(Section);
  2294. UnicodeString LastSourceDir;
  2295. TRemoteThumbnailsQueue & ThumbnailsQueue = FManagedTerminal->ThumbnailsQueue;
  2296. while (Continue() && !ThumbnailsQueue.empty())
  2297. {
  2298. const TRemoteThumbnailNeeded & ThumbnailNeeded = ThumbnailsQueue.front();
  2299. FManagedTerminal->ThumbnailVisibleResult = -1;
  2300. int Index = ThumbnailNeeded.Index;
  2301. std::unique_ptr<TRemoteFile> File(ThumbnailNeeded.File->Duplicate());
  2302. TSize ThumbnailSize = ThumbnailNeeded.ThumbnailSize;
  2303. UnicodeString FileName = File->FullFileName.Unique();
  2304. AppLogFmt(L"Retrieving thumbnail for %s", (FileName));
  2305. FManagedTerminal->ThumbnailVisibleResult = -1;
  2306. FScpExplorer->PostThumbnailVisibleQueueQuery(Index, FileName);
  2307. LastSourceDir = UnixExtractFileDir(FileName);
  2308. {
  2309. TGuard ItemGuard(FSection);
  2310. FInfo->Source = FileName;
  2311. }
  2312. while (Continue() &&
  2313. (FManagedTerminal->ThumbnailVisibleResult < 0))
  2314. {
  2315. TUnguard Unguard(Section);
  2316. Sleep(10);
  2317. }
  2318. if (Continue())
  2319. {
  2320. if (FManagedTerminal->ThumbnailVisibleResult == 0)
  2321. {
  2322. DebugAssert(ThumbnailsQueue.empty() || (&ThumbnailsQueue.front() != &ThumbnailNeeded));
  2323. }
  2324. else if (DebugAlwaysTrue(CheckQueueFront(Index, FileName, ThumbnailSize)))
  2325. {
  2326. std::unique_ptr<TStringList> Files(new TStringList());
  2327. Files->AddObject(FileName, File.get());
  2328. std::unique_ptr<TBitmap> Thumbnail;
  2329. {
  2330. TUnguard Unguard(Section);
  2331. Terminal->CopyToLocal(Files.get(), FTargetDir, FCopyParam, FParams, NULL);
  2332. UnicodeString LocalPath =
  2333. TPath::Combine(FTargetDir, Terminal->ChangeFileName(FCopyParam, UnixExtractFileName(FileName), osRemote, false));
  2334. Thumbnail.reset(GetThumbnail(LocalPath, ThumbnailSize));
  2335. }
  2336. if (CheckQueueFront(Index, FileName, ThumbnailSize))
  2337. {
  2338. TRemoteThumbnailsMap::iterator I = FManagedTerminal->Thumbnails.find(Index);
  2339. if (DebugAlwaysTrue(I != FManagedTerminal->Thumbnails.end()))
  2340. {
  2341. TRemoteThumbnailData & RemoteThumbnailData = I->second;
  2342. if (DebugAlwaysTrue(RemoteThumbnailData.FileName == UnixExtractFileName(FileName)) &&
  2343. DebugAlwaysTrue(RemoteThumbnailData.ThumbnailSize == ThumbnailSize) &&
  2344. DebugAlwaysTrue(RemoteThumbnailData.Thumbnail == NULL))
  2345. {
  2346. RemoteThumbnailData.Thumbnail = Thumbnail.release();
  2347. FManagedTerminal->PopThumbnailQueue();
  2348. FScpExplorer->PostThumbnailDrawRequest(Index);
  2349. }
  2350. }
  2351. }
  2352. }
  2353. }
  2354. }
  2355. {
  2356. TGuard ItemGuard(FSection);
  2357. FInfo->Source = LastSourceDir;
  2358. }
  2359. FManagedTerminal->ThumbnailDownloadQueueItem = NULL;
  2360. }