TerminalManager.cpp 80 KB

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