1
0

WinMain.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <CoreMain.h>
  5. #include <TextsWin.h>
  6. #include <TextsCore.h>
  7. #include <HelpWin.h>
  8. #include "CustomScpExplorer.h"
  9. #include "TerminalManager.h"
  10. #include "NonVisual.h"
  11. #include "Glyphs.h"
  12. #include "ProgParams.h"
  13. #include "Setup.h"
  14. #include "WinConfiguration.h"
  15. #include "GUITools.h"
  16. #include "Tools.h"
  17. #include "WinApi.h"
  18. #include <DateUtils.hpp>
  19. #include <StrUtils.hpp>
  20. //---------------------------------------------------------------------------
  21. #pragma package(smart_init)
  22. //---------------------------------------------------------------------------
  23. void __fastcall GetLoginData(UnicodeString SessionName, TOptions * Options,
  24. TObjectList * DataList, UnicodeString & DownloadFile, bool NeedSession, TForm * LinkedForm, int Flags)
  25. {
  26. bool DefaultsOnly = false;
  27. UnicodeString FolderOrWorkspaceName = DecodeUrlChars(SessionName);
  28. if (StoredSessions->IsFolder(FolderOrWorkspaceName) ||
  29. StoredSessions->IsWorkspace(FolderOrWorkspaceName))
  30. {
  31. StoredSessions->GetFolderOrWorkspace(FolderOrWorkspaceName, DataList);
  32. }
  33. else
  34. {
  35. TSessionData * SessionData =
  36. StoredSessions->ParseUrl(SessionName, Options, DefaultsOnly, &DownloadFile, NULL, NULL, Flags);
  37. DataList->Add(SessionData);
  38. if (DataList->Count == 1)
  39. {
  40. TSessionData * SessionData = DebugNotNull(dynamic_cast<TSessionData *>(DataList->Items[0]));
  41. if (SessionData->SaveOnly)
  42. {
  43. Configuration->Usage->Inc(L"CommandLineSessionSave");
  44. TSessionData * SavedSession = DoSaveSession(SessionData, NULL, true, NULL);
  45. if (SavedSession == NULL)
  46. {
  47. Abort();
  48. }
  49. WinConfiguration->LastStoredSession = SavedSession->Name;
  50. DataList->Clear();
  51. }
  52. else if (!SessionData->PuttyProtocol.IsEmpty())
  53. {
  54. // putty does not support resolving environment variables in session settings
  55. // though it's hardly of any use here.
  56. SessionData->ExpandEnvironmentVariables();
  57. OpenSessionInPutty(GUIConfiguration->PuttyPath, SessionData);
  58. DataList->Clear();
  59. Abort();
  60. }
  61. }
  62. }
  63. if (DefaultsOnly && !NeedSession)
  64. {
  65. // No URL specified on command-line and no explicit command-line parameter
  66. // that requires session was specified => noop
  67. DataList->Clear();
  68. }
  69. else if ((DataList->Count == 0) ||
  70. !dynamic_cast<TSessionData *>(DataList->Items[0])->CanLogin ||
  71. DefaultsOnly)
  72. {
  73. // Note that GetFolderOrWorkspace never returns sites that !CanLogin,
  74. // so we should not get here with more than one site.
  75. // Though we should be good, if we ever do.
  76. // We get here when:
  77. // - we need session for explicit command-line operation
  78. // - after we handle "save" URL.
  79. // - the specified session does not contain enough information to login [= not even hostname]
  80. DebugAssert(DataList->Count <= 1);
  81. if (!DoLoginDialog(DataList, LinkedForm))
  82. {
  83. Abort();
  84. }
  85. }
  86. }
  87. //---------------------------------------------------------------------------
  88. int GetCommandLineParseUrlFlags(TProgramParams * Params)
  89. {
  90. return
  91. pufAllowStoredSiteWithProtocol |
  92. FLAGMASK(!CheckSafe(Params), pufUnsafe);
  93. }
  94. //---------------------------------------------------------------------------
  95. void __fastcall Upload(TTerminal * Terminal, TStrings * FileList, int UseDefaults)
  96. {
  97. UnicodeString TargetDirectory;
  98. TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;
  99. TargetDirectory = UnixIncludeTrailingBackslash(Terminal->CurrentDirectory);
  100. std::unique_ptr<TSessionData> Data(Terminal->SessionData->Clone());
  101. Terminal->FillSessionDataForCode(Data.get());
  102. int Options = coDisableQueue;
  103. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  104. if ((UseDefaults == 0) ||
  105. DoCopyDialog(true, false, FileList, TargetDirectory, &CopyParam, Options,
  106. CopyParamAttrs, Data.get(), NULL, UseDefaults))
  107. {
  108. // Setting parameter overrides only now, otherwise the dialog would present the parametes as non-default
  109. CopyParam.OnceDoneOperation = odoDisconnect;
  110. Terminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, 0, NULL);
  111. }
  112. }
  113. //---------------------------------------------------------------------------
  114. void __fastcall Download(TTerminal * Terminal, const UnicodeString FileName, int UseDefaults)
  115. {
  116. TRemoteFile * File = NULL;
  117. try
  118. {
  119. Terminal->ExceptionOnFail = true;
  120. try
  121. {
  122. Terminal->ReadFile(FileName, File);
  123. }
  124. __finally
  125. {
  126. Terminal->ExceptionOnFail = false;
  127. }
  128. File->FullFileName = FileName;
  129. UnicodeString LocalDirectory = Terminal->SessionData->LocalDirectoryExpanded;
  130. if (LocalDirectory.IsEmpty())
  131. {
  132. LocalDirectory = GetPersonalFolder();
  133. }
  134. UnicodeString TargetDirectory = IncludeTrailingBackslash(LocalDirectory);
  135. TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;
  136. UnicodeString DisplayName = File->FileName;
  137. bool CustomDisplayName =
  138. !File->DisplayName.IsEmpty() &&
  139. (File->DisplayName != DisplayName);
  140. if (CustomDisplayName)
  141. {
  142. DisplayName = File->DisplayName;
  143. }
  144. UnicodeString FriendyFileName = UnixIncludeTrailingBackslash(UnixExtractFilePath(FileName)) + DisplayName;
  145. std::unique_ptr<TStrings> FileListFriendly(new TStringList());
  146. FileListFriendly->AddObject(FriendyFileName, File);
  147. int Options = coDisableQueue;
  148. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Download;
  149. if ((UseDefaults == 0) ||
  150. DoCopyDialog(false, false, FileListFriendly.get(), TargetDirectory, &CopyParam,
  151. Options, CopyParamAttrs, NULL, NULL, UseDefaults))
  152. {
  153. // Setting parameter overrides only now, otherwise the dialog would present the parametes as non-default
  154. if (CustomDisplayName)
  155. {
  156. // Set only now, so that it is not redundantly displayed on the copy dialog.
  157. // We should escape the * and ?'s.
  158. CopyParam.FileMask = DisplayName;
  159. }
  160. CopyParam.OnceDoneOperation = odoDisconnect;
  161. std::unique_ptr<TStrings> FileList(new TStringList());
  162. FileList->AddObject(FileName, File);
  163. Terminal->CopyToLocal(FileList.get(), TargetDirectory, &CopyParam, 0, NULL);
  164. }
  165. UnicodeString Directory = UnixExtractFilePath(FileName);
  166. Terminal->AutoReadDirectory = true;
  167. Terminal->ChangeDirectory(Directory);
  168. }
  169. __finally
  170. {
  171. delete File;
  172. }
  173. }
  174. //---------------------------------------------------------------------------
  175. void __fastcall Edit(TCustomScpExplorerForm * ScpExplorer, TStrings * FileList)
  176. {
  177. ScpExplorer->StandaloneEdit(FileList->Strings[0]);
  178. Abort();
  179. }
  180. //---------------------------------------------------------------------------
  181. void __fastcall SynchronizeDirectories(
  182. TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams,
  183. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory)
  184. {
  185. if (CommandParams->Count >= 1)
  186. {
  187. LocalDirectory = CommandParams->Strings[0];
  188. }
  189. else if (!Terminal->SessionData->LocalDirectory.IsEmpty())
  190. {
  191. LocalDirectory = Terminal->SessionData->LocalDirectoryExpanded;
  192. }
  193. else
  194. {
  195. LocalDirectory = ScpExplorer->DefaultDownloadTargetDirectory();
  196. }
  197. if (CommandParams->Count >= 2)
  198. {
  199. RemoteDirectory = CommandParams->Strings[1];
  200. }
  201. else
  202. {
  203. RemoteDirectory = Terminal->CurrentDirectory;
  204. }
  205. }
  206. //---------------------------------------------------------------------------
  207. void __fastcall FullSynchronize(
  208. TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams, int UseDefaults)
  209. {
  210. UnicodeString LocalDirectory;
  211. UnicodeString RemoteDirectory;
  212. SynchronizeDirectories(Terminal, ScpExplorer, CommandParams, LocalDirectory, RemoteDirectory);
  213. bool SaveMode = true;
  214. // bit ugly
  215. TSynchronizeMode Mode = (TSynchronizeMode)GUIConfiguration->SynchronizeMode;
  216. int Params = GUIConfiguration->SynchronizeParams;
  217. // Undocumented syntax for "Start in New Window"
  218. if (CommandParams->Count >= 4)
  219. {
  220. Mode = (TSynchronizeMode)StrToIntDef(CommandParams->Strings[2], Mode);
  221. Params = StrToIntDef(CommandParams->Strings[3], Params);
  222. }
  223. int Result =
  224. ScpExplorer->DoFullSynchronizeDirectories(LocalDirectory, RemoteDirectory, Mode, Params, SaveMode, UseDefaults);
  225. if ((Result >= 0) && SaveMode)
  226. {
  227. GUIConfiguration->SynchronizeMode = Mode;
  228. }
  229. Abort();
  230. }
  231. //---------------------------------------------------------------------------
  232. void __fastcall Synchronize(
  233. TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams, int UseDefaults)
  234. {
  235. UnicodeString LocalDirectory;
  236. UnicodeString RemoteDirectory;
  237. SynchronizeDirectories(Terminal, ScpExplorer, CommandParams, LocalDirectory, RemoteDirectory);
  238. // Undocumented syntax for "Start in New Window"
  239. if (CommandParams->Count >= 4)
  240. {
  241. GUIConfiguration->SynchronizeParams = StrToIntDef(CommandParams->Strings[2], -1);
  242. GUIConfiguration->SynchronizeOptions = StrToIntDef(CommandParams->Strings[3], -1);
  243. Configuration->DontSave();
  244. }
  245. ScpExplorer->DoSynchronizeDirectories(LocalDirectory, RemoteDirectory, UseDefaults);
  246. Abort();
  247. }
  248. //---------------------------------------------------------------------------
  249. void __fastcall ImportSitesIfAny()
  250. {
  251. if (!WinConfiguration->AutoImportedFromPuttyOrFilezilla)
  252. {
  253. bool AnyPuttySession = GUIConfiguration->AnyPuttySessionForImport(StoredSessions);
  254. bool AnyFilezillaSession = GUIConfiguration->AnyFilezillaSessionForImport(StoredSessions);
  255. if (AnyPuttySession || AnyFilezillaSession)
  256. {
  257. UnicodeString PuttySource = LoadStrPart(IMPORT_SESSIONS2, 2);
  258. UnicodeString FilezillaSource = LoadStrPart(IMPORT_SESSIONS2, 3);
  259. UnicodeString Source;
  260. if (AnyPuttySession && AnyFilezillaSession)
  261. {
  262. Source = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 4), (PuttySource, FilezillaSource));
  263. }
  264. else if (AnyPuttySession)
  265. {
  266. Source = PuttySource;
  267. }
  268. else if (AnyFilezillaSession)
  269. {
  270. Source = FilezillaSource;
  271. }
  272. else
  273. {
  274. DebugFail();
  275. }
  276. UnicodeString Message = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 1), (Source));
  277. if (MessageDialog(Message, qtConfirmation,
  278. qaYes | qaNo, HELP_IMPORT_SESSIONS) == qaYes)
  279. {
  280. DoImportSessionsDialog(NULL);
  281. }
  282. WinConfiguration->AutoImportedFromPuttyOrFilezilla = true;
  283. }
  284. }
  285. }
  286. //---------------------------------------------------------------------------
  287. void __fastcall Usage(UnicodeString Param)
  288. {
  289. while (!Param.IsEmpty())
  290. {
  291. UnicodeString Pair = CutToChar(Param, L',', true);
  292. if (!Pair.IsEmpty())
  293. {
  294. if (Pair[Pair.Length()] == L'+')
  295. {
  296. UnicodeString Key = Pair.SubString(1, Pair.Length() - 1).Trim();
  297. Configuration->Usage->Inc(Key);
  298. }
  299. else if (Pair[Pair.Length()] == L'@')
  300. {
  301. UnicodeString Key = Pair.SubString(1, Pair.Length() - 1).Trim();
  302. UnicodeString Value;
  303. if (SameText(Key, L"InstallationParentProcess"))
  304. {
  305. Value = GetAncestorProcessName(3).LowerCase();
  306. }
  307. else
  308. {
  309. Value = L"err-unknown-key";
  310. }
  311. Configuration->Usage->Set(Key, Value);
  312. }
  313. else
  314. {
  315. UnicodeString Key = CutToChar(Pair, L':', true);
  316. UnicodeString Value = Pair.Trim();
  317. Configuration->Usage->Set(Key, Value);
  318. }
  319. }
  320. }
  321. }
  322. //---------------------------------------------------------------------------
  323. void __fastcall RecordWrapperVersions(UnicodeString ConsoleVersion, UnicodeString DotNetVersion)
  324. {
  325. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  326. if (!DotNetVersion.IsEmpty())
  327. {
  328. Updates.DotNetVersion = DotNetVersion;
  329. }
  330. if (!ConsoleVersion.IsEmpty())
  331. {
  332. Updates.ConsoleVersion = ConsoleVersion;
  333. }
  334. WinConfiguration->Updates = Updates;
  335. if (Configuration->Storage == stNul)
  336. {
  337. Configuration->SetDefaultStorage();
  338. try
  339. {
  340. THierarchicalStorage * Storage = Configuration->CreateConfigStorage();
  341. try
  342. {
  343. Storage->AccessMode = smReadWrite;
  344. if (Storage->OpenSubKey(Configuration->ConfigurationSubKey, true) &&
  345. Storage->OpenSubKeyPath(L"Interface\\Updates", true))
  346. {
  347. if (!DotNetVersion.IsEmpty())
  348. {
  349. Storage->WriteString(L"DotNetVersion", DotNetVersion);
  350. }
  351. if (!ConsoleVersion.IsEmpty())
  352. {
  353. Storage->WriteString(L"ConsoleVersion", ConsoleVersion);
  354. }
  355. }
  356. }
  357. __finally
  358. {
  359. delete Storage;
  360. }
  361. }
  362. __finally
  363. {
  364. Configuration->SetNulStorage();
  365. }
  366. }
  367. }
  368. //---------------------------------------------------------------------------
  369. static UnicodeString ColorToRGBStr(TColor Color)
  370. {
  371. int RGB = ColorToRGB(Color);
  372. int R = GetRValue(RGB);
  373. int G = GetGValue(RGB);
  374. int B = GetBValue(RGB);
  375. UnicodeString Result = FORMAT(L"%.2x%.2x%.2x", (R, G, B));
  376. return Result;
  377. }
  378. //---------------------------------------------------------------------------
  379. TDateTime Started(Now());
  380. int LifetimeRuns = -1;
  381. //---------------------------------------------------------------------------
  382. void InterfaceStartDontMeasure()
  383. {
  384. Started = TDateTime();
  385. }
  386. //---------------------------------------------------------------------------
  387. void InterfaceStarted()
  388. {
  389. if ((Started != TDateTime()) && (LifetimeRuns > 0))
  390. {
  391. // deliberate downcast
  392. int StartupSeconds = static_cast<int>(SecondsBetween(Now(), Started));
  393. if (LifetimeRuns == 1)
  394. {
  395. Configuration->Usage->Set(L"StartupSeconds1", StartupSeconds);
  396. }
  397. else if (LifetimeRuns == 2)
  398. {
  399. Configuration->Usage->Set(L"StartupSeconds2", StartupSeconds);
  400. }
  401. Configuration->Usage->Set(L"StartupSecondsLast", StartupSeconds);
  402. }
  403. }
  404. //---------------------------------------------------------------------------
  405. void __fastcall UpdateStaticUsage()
  406. {
  407. Configuration->Usage->Inc(L"Runs");
  408. Configuration->Usage->UpdateCurrentVersion();
  409. Configuration->Usage->Set(L"WindowsVersion", (WindowsVersionLong()));
  410. Configuration->Usage->Set(L"WindowsProductName", (WindowsProductName()));
  411. DWORD Type;
  412. GetWindowsProductType(Type);
  413. Configuration->Usage->Set(L"WindowsProductType", (static_cast<int>(Type)));
  414. Configuration->Usage->Set(L"Windows64", IsWin64());
  415. Configuration->Usage->Set(L"UWP", IsUWP());
  416. Configuration->Usage->Set(L"DefaultLocale",
  417. // See TGUIConfiguration::GetAppliedLocaleHex()
  418. IntToHex(static_cast<int>(GetDefaultLCID()), 4));
  419. Configuration->Usage->Set(L"Locale", WinConfiguration->AppliedLocaleHex);
  420. Configuration->Usage->Set(L"EncodingMultiByteAnsi", !TEncoding::Default->IsSingleByte);
  421. Configuration->Usage->Set(L"PixelsPerInch", Screen->PixelsPerInch);
  422. bool PixelsPerInchSystemDiffers = false;
  423. bool PixelsPerInchMonitorsDiffer = false;
  424. bool PixelsPerInchAxesDiffer = false;
  425. HINSTANCE ShCoreLibrary = LoadLibrary(L"shcore.dll");
  426. if (ShCoreLibrary != NULL)
  427. {
  428. GetDpiForMonitorProc GetDpiForMonitor =
  429. (GetDpiForMonitorProc)GetProcAddress(ShCoreLibrary, "GetDpiForMonitor");
  430. if (GetDpiForMonitor != NULL)
  431. {
  432. unsigned int PrimaryDpiX;
  433. unsigned int PrimaryDpiY;
  434. for (int Index = 0; Index < Screen->MonitorCount; Index++)
  435. {
  436. unsigned int DpiX;
  437. unsigned int DpiY;
  438. GetDpiForMonitor(Screen->Monitors[Index]->Handle, MDT_Default, &DpiX, &DpiY);
  439. if (DpiX != DpiY)
  440. {
  441. PixelsPerInchAxesDiffer = true;
  442. }
  443. if (Index == 0)
  444. {
  445. PrimaryDpiX = DpiX;
  446. PrimaryDpiY = DpiY;
  447. // PixelsPerInch is GetDeviceCaps(DC, LOGPIXELSY)
  448. if (DpiY != (unsigned int)Screen->PixelsPerInch)
  449. {
  450. PixelsPerInchSystemDiffers = true;
  451. }
  452. }
  453. else
  454. {
  455. if ((DpiX != PrimaryDpiX) ||
  456. (DpiY != PrimaryDpiY))
  457. {
  458. PixelsPerInchMonitorsDiffer = true;
  459. }
  460. }
  461. }
  462. }
  463. }
  464. if (PixelsPerInchSystemDiffers)
  465. {
  466. Configuration->Usage->Inc(L"PixelsPerInchSystemDiffered");
  467. }
  468. Configuration->Usage->Set(L"PixelsPerInchMonitorsDiffer", PixelsPerInchMonitorsDiffer);
  469. Configuration->Usage->Set(L"PixelsPerInchAxesDiffer", PixelsPerInchAxesDiffer);
  470. Configuration->Usage->Set(L"WorkAreaWidth", Screen->WorkAreaWidth);
  471. Configuration->Usage->Set(L"WorkAreaHeight", Screen->WorkAreaHeight);
  472. HDC DC = GetDC(NULL);
  473. int Planes = GetDeviceCaps(DC, PLANES);
  474. int BitsPixel = GetDeviceCaps(DC, BITSPIXEL);
  475. Configuration->Usage->Set(L"ColorDepth", Planes * BitsPixel);
  476. Configuration->Usage->Set(L"MonitorCount", Screen->MonitorCount);
  477. Configuration->Usage->Set(L"NotUseThemes", !UseThemes());
  478. Configuration->Usage->Set(L"ThemeDefaultFontSize", Application->DefaultFont->Size);
  479. Configuration->Usage->Set(L"ThemeIconFontSize", Screen->IconFont->Size);
  480. Configuration->Usage->Set(L"SysColorWindow", ColorToRGBStr(clWindow));
  481. Configuration->Usage->Set(L"SysColorBtnFace", ColorToRGBStr(clBtnFace));
  482. Configuration->Usage->Set(L"SysColorWindowText", ColorToRGBStr(clWindowText));
  483. UnicodeString ProgramsFolder;
  484. ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);
  485. ProgramsFolder = IncludeTrailingBackslash(ExpandFileName(ProgramsFolder));
  486. UnicodeString ExeName = ExpandFileName(Application->ExeName);
  487. bool InProgramFiles = AnsiSameText(ExeName.SubString(1, ProgramsFolder.Length()), ProgramsFolder);
  488. Configuration->Usage->Set(L"InProgramFiles", InProgramFiles);
  489. Configuration->Usage->Set(L"IsInstalled", IsInstalled());
  490. Configuration->Usage->Set(L"Wine", IsWine());
  491. Configuration->Usage->Set(L"NetFrameworkVersion", GetNetVersionStr());
  492. Configuration->Usage->Set(L"NetCoreVersion", GetNetCoreVersionStr());
  493. Configuration->Usage->Set(L"PowerShellVersion", GetPowerShellVersionStr());
  494. Configuration->Usage->Set(L"PwshVersion", GetPowerShellCoreVersionStr());
  495. UnicodeString ParentProcess = GetAncestorProcessName();
  496. // do not record the installer as a parent process
  497. if (!ParentProcess.IsEmpty() &&
  498. (!StartsText(L"winscp-", ParentProcess) || !ContainsText(ParentProcess, L"-setup")))
  499. {
  500. UnicodeString ParentProcesses = Configuration->Usage->Get(L"ParentProcesses");
  501. std::unique_ptr<TStringList> ParentProcessesList(CreateSortedStringList());
  502. ParentProcessesList->CommaText = ParentProcesses;
  503. ParentProcessesList->Add(ParentProcess.LowerCase());
  504. Configuration->Usage->Set(L"ParentProcesses", ParentProcessesList->CommaText);
  505. }
  506. WinConfiguration->UpdateStaticUsage();
  507. }
  508. //---------------------------------------------------------------------------
  509. void __fastcall MaintenanceTask()
  510. {
  511. CoreMaintenanceTask();
  512. }
  513. //---------------------------------------------------------------------------
  514. typedef std::vector<HWND> THandles;
  515. typedef std::map<unsigned long, THandles> TProcesses;
  516. //---------------------------------------------------------------------------
  517. BOOL __stdcall EnumOtherInstances(HWND Handle, LPARAM AParam)
  518. {
  519. TProcesses & Processes = *reinterpret_cast<TProcesses *>(AParam);
  520. unsigned long ProcessId;
  521. if (GetWindowThreadProcessId(Handle, &ProcessId) != 0)
  522. {
  523. Processes[ProcessId].push_back(Handle);
  524. }
  525. return TRUE;
  526. }
  527. //---------------------------------------------------------------------------
  528. static bool __fastcall SendCopyDataMessage(HWND Window, TCopyDataMessage & Message)
  529. {
  530. COPYDATASTRUCT CopyData;
  531. CopyData.cbData = sizeof(Message);
  532. CopyData.lpData = &Message;
  533. LRESULT SendResult =
  534. SendMessage(Window, WM_COPYDATA,
  535. reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));
  536. bool Result = (SendResult > 0);
  537. return Result;
  538. }
  539. //---------------------------------------------------------------------------
  540. static void __fastcall FindOtherInstances(THandles & OtherInstances)
  541. {
  542. TProcesses Processes;
  543. // FindWindow is optimization (if there's no hidden window, no point enumerating all windows to find some)
  544. if ((FindWindow(HIDDEN_WINDOW_NAME, NULL) != NULL) &&
  545. EnumWindows(EnumOtherInstances, reinterpret_cast<LPARAM>(&Processes)))
  546. {
  547. TCopyDataMessage Message;
  548. Message.Command = TCopyDataMessage::MainWindowCheck;
  549. TProcesses::const_iterator ProcessI = Processes.begin();
  550. while (ProcessI != Processes.end())
  551. {
  552. HWND HiddenWindow = NULL;
  553. THandles::const_iterator WindowI = ProcessI->second.begin();
  554. while ((HiddenWindow == NULL) && (WindowI != ProcessI->second.end()))
  555. {
  556. wchar_t ClassName[1024];
  557. if (GetClassName(*WindowI, ClassName, LENOF(ClassName)) != 0)
  558. {
  559. NULL_TERMINATE(ClassName);
  560. if (wcscmp(ClassName, HIDDEN_WINDOW_NAME) == 0)
  561. {
  562. HiddenWindow = *WindowI;
  563. }
  564. }
  565. WindowI++;
  566. }
  567. if (HiddenWindow != NULL)
  568. {
  569. WindowI = ProcessI->second.begin();
  570. while (WindowI != ProcessI->second.end())
  571. {
  572. if (*WindowI != HiddenWindow) // optimization
  573. {
  574. if (SendCopyDataMessage(*WindowI, Message))
  575. {
  576. OtherInstances.push_back(*WindowI);
  577. break;
  578. }
  579. }
  580. WindowI++;
  581. }
  582. }
  583. ProcessI++;
  584. }
  585. }
  586. }
  587. //---------------------------------------------------------------------------
  588. bool __fastcall SendToAnotherInstance()
  589. {
  590. THandles OtherInstances;
  591. FindOtherInstances(OtherInstances);
  592. bool Result = false;
  593. THandles::const_iterator I = OtherInstances.begin();
  594. while (!Result && (I != OtherInstances.end()))
  595. {
  596. HWND Handle = *I;
  597. TCopyDataMessage Message;
  598. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  599. if (SendCopyDataMessage(Handle, Message))
  600. {
  601. // Restore window, if minimized
  602. ShowWindow(Handle, SW_RESTORE);
  603. // bring it to foreground
  604. SetForegroundWindow(Handle);
  605. Message.Command = TCopyDataMessage::CommandCommandLine;
  606. wcsncpy(Message.CommandLine, CmdLine, LENOF(Message.CommandLine));
  607. NULL_TERMINATE(Message.CommandLine);
  608. Result = SendCopyDataMessage(Handle, Message);
  609. }
  610. I++;
  611. }
  612. return Result;
  613. }
  614. //---------------------------------------------------------------------------
  615. void __fastcall Refresh(const UnicodeString & Session, const UnicodeString & Path)
  616. {
  617. THandles OtherInstances;
  618. FindOtherInstances(OtherInstances);
  619. THandles::const_iterator I = OtherInstances.begin();
  620. while (I != OtherInstances.end())
  621. {
  622. HWND Handle = *I;
  623. TCopyDataMessage Message;
  624. Message.Command = TCopyDataMessage::RefreshPanel;
  625. wcsncpy(Message.Refresh.Session, Session.c_str(), LENOF(Message.Refresh.Session));
  626. NULL_TERMINATE(Message.Refresh.Session);
  627. wcsncpy(Message.Refresh.Path, Path.c_str(), LENOF(Message.Refresh.Path));
  628. NULL_TERMINATE(Message.Refresh.Path);
  629. SendCopyDataMessage(Handle, Message);
  630. I++;
  631. }
  632. }
  633. //---------------------------------------------------------------------------
  634. bool __fastcall ShowUpdatesIfAvailable()
  635. {
  636. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  637. int CurrentCompoundVer = Configuration->CompoundVersion;
  638. bool NoPopup = true;
  639. bool Result =
  640. !IsUWP() &&
  641. Updates.ShowOnStartup &&
  642. Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&
  643. !Updates.Results.Disabled &&
  644. ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&
  645. !Updates.ShownResults;
  646. if (Result)
  647. {
  648. Configuration->Usage->Inc(L"UpdateStartup");
  649. Result = CheckForUpdates(true);
  650. if (Result)
  651. {
  652. Configuration->Usage->Inc(L"UpdateDownloadOpensStartup");
  653. }
  654. NoPopup = false;
  655. }
  656. else if (WinConfiguration->ShowTips)
  657. {
  658. int Days = DaysBetween(WinConfiguration->TipsShown, Now());
  659. if ((Days >= Updates.Results.TipsIntervalDays) &&
  660. (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))
  661. {
  662. UnicodeString Tip = FirstUnshownTip();
  663. if (!Tip.IsEmpty())
  664. {
  665. AutoShowNewTip();
  666. NoPopup = false;
  667. }
  668. else
  669. {
  670. Configuration->Usage->Inc(L"TipsNoUnseen");
  671. }
  672. }
  673. }
  674. if (NoPopup)
  675. {
  676. WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;
  677. }
  678. return Result;
  679. }
  680. //---------------------------------------------------------------------------
  681. int __fastcall Execute()
  682. {
  683. DebugAssert(StoredSessions);
  684. TProgramParams * Params = TProgramParams::Instance();
  685. DebugAssert(Params);
  686. // do not flash message boxes on startup
  687. SetOnForeground(true);
  688. // let installer know, that some instance of application is running
  689. CreateMutex(NULL, False, AppName.c_str());
  690. bool OnlyInstance = (GetLastError() == 0);
  691. UpdateStaticUsage();
  692. UnicodeString KeyFile;
  693. if (Params->FindSwitch(L"PrivateKey", KeyFile))
  694. {
  695. WinConfiguration->DefaultKeyFile = KeyFile;
  696. }
  697. UnicodeString ConsoleVersion;
  698. UnicodeString DotNetVersion;
  699. Params->FindSwitch(L"Console", ConsoleVersion);
  700. Params->FindSwitch(L"DotNet", DotNetVersion);
  701. if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())
  702. {
  703. RecordWrapperVersions(ConsoleVersion, DotNetVersion);
  704. }
  705. if (!DotNetVersion.IsEmpty())
  706. {
  707. Configuration->Usage->Inc(L"ConsoleDotNet");
  708. }
  709. UnicodeString SwitchValue;
  710. if (Params->FindSwitch(L"loglevel", SwitchValue))
  711. {
  712. int StarPos = SwitchValue.Pos(L"*");
  713. if (StarPos > 0)
  714. {
  715. bool LogSensitive = true;
  716. SwitchValue.Delete(StarPos, 1);
  717. if ((StarPos <= SwitchValue.Length()) &&
  718. (SwitchValue[StarPos] == L'-'))
  719. {
  720. LogSensitive = false;
  721. SwitchValue.Delete(StarPos, 1);
  722. }
  723. SwitchValue = SwitchValue.Trim();
  724. Configuration->TemporaryLogSensitive(LogSensitive);
  725. }
  726. int LogProtocol;
  727. if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= -1))
  728. {
  729. Configuration->TemporaryLogProtocol(LogProtocol);
  730. }
  731. }
  732. if (Params->FindSwitch(LOGSIZE_SWITCH, SwitchValue))
  733. {
  734. int StarPos = SwitchValue.Pos(LOGSIZE_SEPARATOR);
  735. int LogMaxCount = 0;
  736. if (StarPos > 1)
  737. {
  738. if (!TryStrToInt(SwitchValue.SubString(1, StarPos - 1), LogMaxCount))
  739. {
  740. LogMaxCount = -1;
  741. }
  742. SwitchValue.Delete(1, StarPos);
  743. SwitchValue = SwitchValue.Trim();
  744. }
  745. __int64 LogMaxSize;
  746. if ((LogMaxCount >= 0) &&
  747. !SwitchValue.IsEmpty() &&
  748. TryStrToSize(SwitchValue, LogMaxSize))
  749. {
  750. Configuration->TemporaryLogMaxCount(LogMaxCount);
  751. Configuration->TemporaryLogMaxSize(LogMaxSize);
  752. }
  753. }
  754. std::unique_ptr<TStrings> RawSettings(new TStringList());
  755. if (Params->FindSwitch(RAWTRANSFERSETTINGS_SWITCH, RawSettings.get()))
  756. {
  757. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings.get(), false));
  758. GUIConfiguration->LoadDefaultCopyParam(OptionsStorage.get());
  759. }
  760. TConsoleMode Mode = cmNone;
  761. if (Params->FindSwitch(L"help") || Params->FindSwitch(L"h") || Params->FindSwitch(L"?"))
  762. {
  763. Mode = cmHelp;
  764. }
  765. else if (Params->FindSwitch(L"batchsettings"))
  766. {
  767. Mode = cmBatchSettings;
  768. }
  769. else if (Params->FindSwitch(KEYGEN_SWITCH))
  770. {
  771. Mode = cmKeyGen;
  772. }
  773. else if (Params->FindSwitch(FINGERPRINTSCAN_SWITCH))
  774. {
  775. Mode = cmFingerprintScan;
  776. }
  777. else if (Params->FindSwitch(DUMPCALLSTACK_SWITCH))
  778. {
  779. Mode = cmDumpCallstack;
  780. }
  781. else if (Params->FindSwitch(INFO_SWITCH))
  782. {
  783. Mode = cmInfo;
  784. }
  785. else if (Params->FindSwitch(COMREGISTRATION_SWITCH))
  786. {
  787. Mode = cmComRegistration;
  788. }
  789. // We have to check for /console only after the other options,
  790. // as the /console is always used when we are run by winscp.com
  791. // (ambiguous use to pass console version)
  792. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(SCRIPT_SWITCH) ||
  793. Params->FindSwitch(COMMAND_SWITCH))
  794. {
  795. Mode = cmScripting;
  796. }
  797. if (Mode != cmNone)
  798. {
  799. return Console(Mode);
  800. }
  801. TTerminalManager * TerminalManager = NULL;
  802. GlyphsModule = NULL;
  803. NonVisualDataModule = NULL;
  804. TStrings * CommandParams = new TStringList;
  805. try
  806. {
  807. TerminalManager = TTerminalManager::Instance();
  808. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  809. try
  810. {
  811. GlyphsModule = new TGlyphsModule(Application);
  812. }
  813. __finally
  814. {
  815. GUIConfiguration->ChangeResourceModule(ResourceModule);
  816. }
  817. NonVisualDataModule = new TNonVisualDataModule(Application);
  818. // The default is 2.5s.
  819. // 20s is used by Office 2010 and Windows 10 Explorer.
  820. // Some applications use an infinite (Thunderbird, Firefox).
  821. // Overriden for some controls using THintInfo.HideTimeout
  822. Application->HintHidePause = 20000;
  823. HintWindowClass = __classid(TScreenTipHintWindow);
  824. UnicodeString IniFileName = Params->SwitchValue(INI_SWITCH);
  825. if (!IniFileName.IsEmpty() && (IniFileName != INI_NUL))
  826. {
  827. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  828. if (!FileExists(ApiPath(IniFileNameExpanded)))
  829. {
  830. // this should be displayed rather at the very beginning.
  831. // however for simplicity (GUI-only), we do it only here.
  832. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  833. }
  834. }
  835. if (Params->FindSwitch(L"UninstallCleanup"))
  836. {
  837. MaintenanceTask();
  838. Configuration->DontSave();
  839. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  840. // workaround is that we create mutex in uninstaller, if it runs silent, and
  841. // ignore the UninstallCleanup, when the mutex exists.
  842. if (OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL)
  843. {
  844. DoCleanupDialogIfAnyDataAndWanted();
  845. }
  846. }
  847. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  848. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  849. {
  850. MaintenanceTask();
  851. if (CheckSafe(Params))
  852. {
  853. RegisterForDefaultProtocols();
  854. Configuration->DontSave();
  855. }
  856. }
  857. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  858. {
  859. MaintenanceTask();
  860. if (CheckSafe(Params))
  861. {
  862. UnregisterForProtocols();
  863. Configuration->DontSave();
  864. }
  865. }
  866. else if (Params->FindSwitch(L"AddSearchPath"))
  867. {
  868. MaintenanceTask();
  869. if (CheckSafe(Params))
  870. {
  871. AddSearchPath(ExtractFilePath(Application->ExeName));
  872. Configuration->DontSave();
  873. }
  874. }
  875. else if (Params->FindSwitch(L"RemoveSearchPath"))
  876. {
  877. MaintenanceTask();
  878. if (CheckSafe(Params))
  879. {
  880. try
  881. {
  882. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  883. }
  884. catch(...)
  885. {
  886. // ignore errors
  887. // (RemoveSearchPath is called always on uninstallation,
  888. // even if AddSearchPath was not used, so we would get the error
  889. // always for non-priviledged user)
  890. }
  891. Configuration->DontSave();
  892. }
  893. }
  894. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  895. {
  896. MaintenanceTask();
  897. ImportSitesIfAny();
  898. }
  899. else if (Params->FindSwitch(L"Usage", SwitchValue))
  900. {
  901. MaintenanceTask();
  902. Usage(SwitchValue);
  903. }
  904. else if (Params->FindSwitch(L"Update"))
  905. {
  906. MaintenanceTask();
  907. CheckForUpdates(false);
  908. }
  909. else if (ShowUpdatesIfAvailable())
  910. {
  911. // noop
  912. }
  913. else if (Params->FindSwitch(L"Exit"))
  914. {
  915. // noop
  916. MaintenanceTask();
  917. Configuration->DontSave();
  918. }
  919. else if (Params->FindSwitch(L"MaintenanceTask"))
  920. {
  921. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  922. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  923. MaintenanceTask();
  924. Configuration->DontSave();
  925. }
  926. else
  927. {
  928. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit, pcRefresh } ParamCommand;
  929. ParamCommand = pcNone;
  930. UnicodeString AutoStartSession;
  931. UnicodeString DownloadFile;
  932. int UseDefaults = -1;
  933. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  934. if (OnlyInstance &&
  935. WinConfiguration->TemporaryDirectoryCleanup)
  936. {
  937. TemporaryDirectoryCleanup();
  938. }
  939. WinConfiguration->CheckDefaultTranslation();
  940. // Loading shell image lists here (rather than only on demand when file controls are being created)
  941. // reduces risk of an occasional crash.
  942. // It seems that the point is to load the lists before any call to SHGetFileInfoWithTimeout.
  943. InitFileControls();
  944. if (!Params->Empty)
  945. {
  946. UnicodeString Value;
  947. if (Params->FindSwitch(DEFAULTS_SWITCH, Value) && CheckSafe(Params))
  948. {
  949. UseDefaults = StrToIntDef(Value, 0);
  950. }
  951. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  952. {
  953. ParamCommand = pcUpload;
  954. if (CommandParams->Count == 0)
  955. {
  956. throw Exception(NO_UPLOAD_LIST_ERROR);
  957. }
  958. }
  959. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  960. {
  961. if (CommandParams->Count > 0)
  962. {
  963. ParamCommand = pcUpload;
  964. }
  965. }
  966. else if (Params->FindSwitch(SYNCHRONIZE_SWITCH, CommandParams, 4))
  967. {
  968. ParamCommand = pcFullSynchronize;
  969. }
  970. else if (Params->FindSwitch(KEEP_UP_TO_DATE_SWITCH, CommandParams, 4))
  971. {
  972. ParamCommand = pcSynchronize;
  973. }
  974. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  975. (CommandParams->Count == 1))
  976. {
  977. ParamCommand = pcEdit;
  978. }
  979. else if (Params->FindSwitch(REFRESH_SWITCH, CommandParams, 1))
  980. {
  981. ParamCommand = pcRefresh;
  982. }
  983. }
  984. if (Params->ParamCount > 0)
  985. {
  986. AutoStartSession = Params->Param[1];
  987. Params->ParamsProcessed(1, 1);
  988. if ((ParamCommand == pcNone) &&
  989. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  990. !Params->FindSwitch(NEWINSTANCE_SWICH) &&
  991. SendToAnotherInstance())
  992. {
  993. Configuration->Usage->Inc(L"SendToAnotherInstance");
  994. return 0;
  995. }
  996. UnicodeString CounterName;
  997. if (Params->FindSwitch(JUMPLIST_SWITCH))
  998. {
  999. CounterName = L"CommandLineJumpList";
  1000. }
  1001. else if (Params->FindSwitch(DESKTOP_SWITCH))
  1002. {
  1003. CounterName = L"CommandLineDesktop";
  1004. }
  1005. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  1006. {
  1007. CounterName = L"CommandLineSendToHook";
  1008. }
  1009. else
  1010. {
  1011. CounterName = L"CommandLineSession2";
  1012. }
  1013. Configuration->Usage->Inc(CounterName);
  1014. }
  1015. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  1016. {
  1017. AutoStartSession = StoredSessions->Sessions[0]->Name;
  1018. }
  1019. else
  1020. {
  1021. AutoStartSession = WinConfiguration->AutoStartSession;
  1022. }
  1023. if (ParamCommand == pcRefresh)
  1024. {
  1025. Refresh(AutoStartSession, (CommandParams->Count > 0 ? CommandParams->Strings[0] : UnicodeString()));
  1026. return 0;
  1027. }
  1028. // from now flash message boxes on background
  1029. SetOnForeground(false);
  1030. bool NeedSession = (ParamCommand != pcNone);
  1031. bool Retry;
  1032. do
  1033. {
  1034. Retry = false;
  1035. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1036. try
  1037. {
  1038. int Flags = GetCommandLineParseUrlFlags(Params);
  1039. GetLoginData(AutoStartSession, Params, DataList.get(), DownloadFile, NeedSession, NULL, Flags);
  1040. // GetLoginData now Aborts when session is needed and none is selected
  1041. if (DebugAlwaysTrue(!NeedSession || (DataList->Count > 0)))
  1042. {
  1043. if (CheckSafe(Params))
  1044. {
  1045. UnicodeString LogFile;
  1046. if (Params->FindSwitch(LOG_SWITCH, LogFile))
  1047. {
  1048. Configuration->TemporaryLogging(LogFile);
  1049. }
  1050. if (Params->FindSwitch(L"XmlLog", LogFile))
  1051. {
  1052. Configuration->TemporaryActionsLogging(LogFile);
  1053. }
  1054. }
  1055. try
  1056. {
  1057. DebugAssert(!TerminalManager->ActiveTerminal);
  1058. bool CanStart;
  1059. bool Browse = false;
  1060. if (DataList->Count > 0)
  1061. {
  1062. TManagedTerminal * Terminal = TerminalManager->NewTerminals(DataList.get());
  1063. UnicodeString BrowseFile;
  1064. if (Params->FindSwitch(BROWSE_SWITCH, BrowseFile) &&
  1065. (!BrowseFile.IsEmpty() || !DownloadFile.IsEmpty()))
  1066. {
  1067. if (BrowseFile.IsEmpty())
  1068. {
  1069. BrowseFile = DownloadFile;
  1070. }
  1071. DebugAssert(Terminal->RemoteExplorerState == NULL);
  1072. Terminal->RemoteExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);
  1073. DebugAssert(Terminal->LocalExplorerState == NULL);
  1074. Terminal->LocalExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);
  1075. DownloadFile = UnicodeString();
  1076. Browse = true;
  1077. }
  1078. if (!DownloadFile.IsEmpty())
  1079. {
  1080. Terminal->AutoReadDirectory = false;
  1081. DownloadFile = UnixIncludeTrailingBackslash(Terminal->SessionData->RemoteDirectory) + DownloadFile;
  1082. Terminal->SessionData->RemoteDirectory = L"";
  1083. Terminal->StateData->RemoteDirectory = Terminal->SessionData->RemoteDirectory;
  1084. }
  1085. TerminalManager->ActiveTerminal = Terminal;
  1086. CanStart = (TerminalManager->Count > 0);
  1087. }
  1088. else
  1089. {
  1090. DebugAssert(!NeedSession);
  1091. CanStart = true;
  1092. }
  1093. if (!CanStart)
  1094. {
  1095. // do not prompt with login dialog, if connection of
  1096. // auto-start session (typically from command line) failed
  1097. if (AutoStartSession.IsEmpty())
  1098. {
  1099. Retry = true;
  1100. }
  1101. }
  1102. else
  1103. {
  1104. // from now on, we do not support runtime interface change
  1105. CustomWinConfiguration->CanApplyInterfaceImmediately = false;
  1106. TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();
  1107. CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;
  1108. try
  1109. {
  1110. // moved inside try .. __finally, because it can fail as well
  1111. TerminalManager->ScpExplorer = ScpExplorer;
  1112. if ((ParamCommand != pcNone) || !DownloadFile.IsEmpty())
  1113. {
  1114. Configuration->Usage->Inc(L"CommandLineOperation");
  1115. ScpExplorer->StandaloneOperation = true;
  1116. }
  1117. if (ParamCommand == pcUpload)
  1118. {
  1119. Upload(TerminalManager->ActiveTerminal, CommandParams, UseDefaults);
  1120. }
  1121. else if (ParamCommand == pcFullSynchronize)
  1122. {
  1123. FullSynchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  1124. CommandParams, UseDefaults);
  1125. }
  1126. else if (ParamCommand == pcSynchronize)
  1127. {
  1128. Synchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  1129. CommandParams, UseDefaults);
  1130. }
  1131. else if (ParamCommand == pcEdit)
  1132. {
  1133. Edit(ScpExplorer, CommandParams);
  1134. }
  1135. else if (!DownloadFile.IsEmpty())
  1136. {
  1137. Download(TerminalManager->ActiveTerminal, DownloadFile,
  1138. UseDefaults);
  1139. }
  1140. else
  1141. {
  1142. if (DataList->Count == 0)
  1143. {
  1144. LifetimeRuns = Configuration->Usage->Inc(L"RunsNormal");
  1145. }
  1146. }
  1147. ScpExplorer->StandaloneOperation = false;
  1148. if (Browse)
  1149. {
  1150. ScpExplorer->BrowseFile();
  1151. }
  1152. Application->Run();
  1153. // to allow dialog boxes show later (like from CheckConfigurationForceSave)
  1154. SetAppTerminated(False);
  1155. }
  1156. __finally
  1157. {
  1158. TerminalManager->ScpExplorer = NULL;
  1159. SAFE_DESTROY(ScpExplorer);
  1160. }
  1161. }
  1162. }
  1163. catch (Exception &E)
  1164. {
  1165. ShowExtendedException(&E);
  1166. }
  1167. }
  1168. }
  1169. // Catch EAbort from Synchronize() and similar functions, so that CheckConfigurationForceSave is processed
  1170. catch (EAbort & E)
  1171. {
  1172. Retry = false; // unlikely to be true, but just in case
  1173. }
  1174. }
  1175. while (Retry);
  1176. }
  1177. // In GUI mode only
  1178. CheckConfigurationForceSave();
  1179. }
  1180. __finally
  1181. {
  1182. delete NonVisualDataModule;
  1183. NonVisualDataModule = NULL;
  1184. ReleaseImagesModules();
  1185. delete GlyphsModule;
  1186. GlyphsModule = NULL;
  1187. TTerminalManager::DestroyInstance();
  1188. delete CommandParams;
  1189. }
  1190. return 0;
  1191. }