WinMain.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  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"PackageName", GetPackageName());
  417. Configuration->Usage->Set(L"DefaultLocale",
  418. // See TGUIConfiguration::GetAppliedLocaleHex()
  419. IntToHex(static_cast<int>(GetDefaultLCID()), 4));
  420. Configuration->Usage->Set(L"Locale", WinConfiguration->AppliedLocaleHex);
  421. Configuration->Usage->Set(L"EncodingMultiByteAnsi", !TEncoding::Default->IsSingleByte);
  422. Configuration->Usage->Set(L"PixelsPerInch", Screen->PixelsPerInch);
  423. bool PixelsPerInchSystemDiffers = false;
  424. bool PixelsPerInchMonitorsDiffer = false;
  425. bool PixelsPerInchAxesDiffer = false;
  426. HINSTANCE ShCoreLibrary = LoadLibrary(L"shcore.dll");
  427. if (ShCoreLibrary != NULL)
  428. {
  429. GetDpiForMonitorProc GetDpiForMonitor =
  430. (GetDpiForMonitorProc)GetProcAddress(ShCoreLibrary, "GetDpiForMonitor");
  431. if (GetDpiForMonitor != NULL)
  432. {
  433. unsigned int PrimaryDpiX;
  434. unsigned int PrimaryDpiY;
  435. for (int Index = 0; Index < Screen->MonitorCount; Index++)
  436. {
  437. unsigned int DpiX;
  438. unsigned int DpiY;
  439. GetDpiForMonitor(Screen->Monitors[Index]->Handle, MDT_Default, &DpiX, &DpiY);
  440. if (DpiX != DpiY)
  441. {
  442. PixelsPerInchAxesDiffer = true;
  443. }
  444. if (Index == 0)
  445. {
  446. PrimaryDpiX = DpiX;
  447. PrimaryDpiY = DpiY;
  448. // PixelsPerInch is GetDeviceCaps(DC, LOGPIXELSY)
  449. if (DpiY != (unsigned int)Screen->PixelsPerInch)
  450. {
  451. PixelsPerInchSystemDiffers = true;
  452. }
  453. }
  454. else
  455. {
  456. if ((DpiX != PrimaryDpiX) ||
  457. (DpiY != PrimaryDpiY))
  458. {
  459. PixelsPerInchMonitorsDiffer = true;
  460. }
  461. }
  462. }
  463. }
  464. }
  465. if (PixelsPerInchSystemDiffers)
  466. {
  467. Configuration->Usage->Inc(L"PixelsPerInchSystemDiffered");
  468. }
  469. Configuration->Usage->Set(L"PixelsPerInchMonitorsDiffer", PixelsPerInchMonitorsDiffer);
  470. Configuration->Usage->Set(L"PixelsPerInchAxesDiffer", PixelsPerInchAxesDiffer);
  471. Configuration->Usage->Set(L"WorkAreaWidth", Screen->WorkAreaWidth);
  472. Configuration->Usage->Set(L"WorkAreaHeight", Screen->WorkAreaHeight);
  473. HDC DC = GetDC(NULL);
  474. int Planes = GetDeviceCaps(DC, PLANES);
  475. int BitsPixel = GetDeviceCaps(DC, BITSPIXEL);
  476. Configuration->Usage->Set(L"ColorDepth", Planes * BitsPixel);
  477. Configuration->Usage->Set(L"MonitorCount", Screen->MonitorCount);
  478. Configuration->Usage->Set(L"NotUseThemes", !UseThemes());
  479. Configuration->Usage->Set(L"ThemeDefaultFontSize", Application->DefaultFont->Size);
  480. Configuration->Usage->Set(L"ThemeIconFontSize", Screen->IconFont->Size);
  481. Configuration->Usage->Set(L"SysColorWindow", ColorToRGBStr(clWindow));
  482. Configuration->Usage->Set(L"SysColorBtnFace", ColorToRGBStr(clBtnFace));
  483. Configuration->Usage->Set(L"SysColorWindowText", ColorToRGBStr(clWindowText));
  484. UnicodeString ProgramsFolder;
  485. ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);
  486. ProgramsFolder = IncludeTrailingBackslash(ExpandFileName(ProgramsFolder));
  487. UnicodeString ExeName = ExpandFileName(Application->ExeName);
  488. bool InProgramFiles = AnsiSameText(ExeName.SubString(1, ProgramsFolder.Length()), ProgramsFolder);
  489. Configuration->Usage->Set(L"InProgramFiles", InProgramFiles);
  490. Configuration->Usage->Set(L"IsInstalled", IsInstalled());
  491. Configuration->Usage->Set(L"Wine", IsWine());
  492. Configuration->Usage->Set(L"NetFrameworkVersion", GetNetVersionStr());
  493. Configuration->Usage->Set(L"NetCoreVersion", GetNetCoreVersionStr());
  494. Configuration->Usage->Set(L"PowerShellVersion", GetPowerShellVersionStr());
  495. Configuration->Usage->Set(L"PwshVersion", GetPowerShellCoreVersionStr());
  496. UnicodeString ParentProcess = GetAncestorProcessName();
  497. // do not record the installer as a parent process
  498. if (!ParentProcess.IsEmpty() &&
  499. (!StartsText(L"winscp-", ParentProcess) || !ContainsText(ParentProcess, L"-setup")))
  500. {
  501. UnicodeString ParentProcesses = Configuration->Usage->Get(L"ParentProcesses");
  502. std::unique_ptr<TStringList> ParentProcessesList(CreateSortedStringList());
  503. ParentProcessesList->CommaText = ParentProcesses;
  504. ParentProcessesList->Add(ParentProcess.LowerCase());
  505. Configuration->Usage->Set(L"ParentProcesses", ParentProcessesList->CommaText);
  506. }
  507. WinConfiguration->UpdateStaticUsage();
  508. }
  509. //---------------------------------------------------------------------------
  510. void __fastcall MaintenanceTask()
  511. {
  512. CoreMaintenanceTask();
  513. }
  514. //---------------------------------------------------------------------------
  515. typedef std::vector<HWND> THandles;
  516. typedef std::map<unsigned long, THandles> TProcesses;
  517. //---------------------------------------------------------------------------
  518. BOOL __stdcall EnumOtherInstances(HWND Handle, LPARAM AParam)
  519. {
  520. TProcesses & Processes = *reinterpret_cast<TProcesses *>(AParam);
  521. unsigned long ProcessId;
  522. if (GetWindowThreadProcessId(Handle, &ProcessId) != 0)
  523. {
  524. Processes[ProcessId].push_back(Handle);
  525. }
  526. return TRUE;
  527. }
  528. //---------------------------------------------------------------------------
  529. static bool __fastcall SendCopyDataMessage(HWND Window, TCopyDataMessage & Message)
  530. {
  531. COPYDATASTRUCT CopyData;
  532. CopyData.cbData = sizeof(Message);
  533. CopyData.lpData = &Message;
  534. LRESULT SendResult =
  535. SendMessage(Window, WM_COPYDATA,
  536. reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));
  537. bool Result = (SendResult > 0);
  538. return Result;
  539. }
  540. //---------------------------------------------------------------------------
  541. static void __fastcall FindOtherInstances(THandles & OtherInstances)
  542. {
  543. TProcesses Processes;
  544. // FindWindow is optimization (if there's no hidden window, no point enumerating all windows to find some)
  545. if ((FindWindow(HIDDEN_WINDOW_NAME, NULL) != NULL) &&
  546. EnumWindows(EnumOtherInstances, reinterpret_cast<LPARAM>(&Processes)))
  547. {
  548. TCopyDataMessage Message;
  549. Message.Command = TCopyDataMessage::MainWindowCheck;
  550. TProcesses::const_iterator ProcessI = Processes.begin();
  551. while (ProcessI != Processes.end())
  552. {
  553. HWND HiddenWindow = NULL;
  554. THandles::const_iterator WindowI = ProcessI->second.begin();
  555. while ((HiddenWindow == NULL) && (WindowI != ProcessI->second.end()))
  556. {
  557. wchar_t ClassName[1024];
  558. if (GetClassName(*WindowI, ClassName, LENOF(ClassName)) != 0)
  559. {
  560. NULL_TERMINATE(ClassName);
  561. if (wcscmp(ClassName, HIDDEN_WINDOW_NAME) == 0)
  562. {
  563. HiddenWindow = *WindowI;
  564. }
  565. }
  566. WindowI++;
  567. }
  568. if (HiddenWindow != NULL)
  569. {
  570. WindowI = ProcessI->second.begin();
  571. while (WindowI != ProcessI->second.end())
  572. {
  573. if (*WindowI != HiddenWindow) // optimization
  574. {
  575. if (SendCopyDataMessage(*WindowI, Message))
  576. {
  577. OtherInstances.push_back(*WindowI);
  578. break;
  579. }
  580. }
  581. WindowI++;
  582. }
  583. }
  584. ProcessI++;
  585. }
  586. }
  587. }
  588. //---------------------------------------------------------------------------
  589. bool __fastcall SendToAnotherInstance()
  590. {
  591. THandles OtherInstances;
  592. FindOtherInstances(OtherInstances);
  593. bool Result = false;
  594. THandles::const_iterator I = OtherInstances.begin();
  595. while (!Result && (I != OtherInstances.end()))
  596. {
  597. HWND Handle = *I;
  598. TCopyDataMessage Message;
  599. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  600. if (SendCopyDataMessage(Handle, Message))
  601. {
  602. // Restore window, if minimized
  603. ShowWindow(Handle, SW_RESTORE);
  604. // bring it to foreground
  605. SetForegroundWindow(Handle);
  606. Message.Command = TCopyDataMessage::CommandCommandLine;
  607. wcsncpy(Message.CommandLine, CmdLine, LENOF(Message.CommandLine));
  608. NULL_TERMINATE(Message.CommandLine);
  609. Result = SendCopyDataMessage(Handle, Message);
  610. }
  611. I++;
  612. }
  613. return Result;
  614. }
  615. //---------------------------------------------------------------------------
  616. void __fastcall Refresh(const UnicodeString & Session, const UnicodeString & Path)
  617. {
  618. THandles OtherInstances;
  619. FindOtherInstances(OtherInstances);
  620. THandles::const_iterator I = OtherInstances.begin();
  621. while (I != OtherInstances.end())
  622. {
  623. HWND Handle = *I;
  624. TCopyDataMessage Message;
  625. Message.Command = TCopyDataMessage::RefreshPanel;
  626. wcsncpy(Message.Refresh.Session, Session.c_str(), LENOF(Message.Refresh.Session));
  627. NULL_TERMINATE(Message.Refresh.Session);
  628. wcsncpy(Message.Refresh.Path, Path.c_str(), LENOF(Message.Refresh.Path));
  629. NULL_TERMINATE(Message.Refresh.Path);
  630. SendCopyDataMessage(Handle, Message);
  631. I++;
  632. }
  633. }
  634. //---------------------------------------------------------------------------
  635. bool __fastcall ShowUpdatesIfAvailable()
  636. {
  637. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  638. int CurrentCompoundVer = Configuration->CompoundVersion;
  639. bool NoPopup = true;
  640. bool Result =
  641. !IsUWP() &&
  642. Updates.ShowOnStartup &&
  643. Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&
  644. !Updates.Results.Disabled &&
  645. ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&
  646. !Updates.ShownResults;
  647. if (Result)
  648. {
  649. Configuration->Usage->Inc(L"UpdateStartup");
  650. Result = CheckForUpdates(true);
  651. if (Result)
  652. {
  653. Configuration->Usage->Inc(L"UpdateDownloadOpensStartup");
  654. }
  655. NoPopup = false;
  656. }
  657. else if (WinConfiguration->ShowTips)
  658. {
  659. int Days = DaysBetween(WinConfiguration->TipsShown, Now());
  660. if ((Days >= Updates.Results.TipsIntervalDays) &&
  661. (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))
  662. {
  663. UnicodeString Tip = FirstUnshownTip();
  664. if (!Tip.IsEmpty())
  665. {
  666. AutoShowNewTip();
  667. NoPopup = false;
  668. }
  669. else
  670. {
  671. Configuration->Usage->Inc(L"TipsNoUnseen");
  672. }
  673. }
  674. }
  675. if (NoPopup)
  676. {
  677. WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;
  678. }
  679. return Result;
  680. }
  681. //---------------------------------------------------------------------------
  682. int __fastcall Execute()
  683. {
  684. DebugAssert(StoredSessions);
  685. TProgramParams * Params = TProgramParams::Instance();
  686. DebugAssert(Params);
  687. // do not flash message boxes on startup
  688. SetOnForeground(true);
  689. // let installer know, that some instance of application is running
  690. CreateMutex(NULL, False, AppName.c_str());
  691. bool OnlyInstance = (GetLastError() == 0);
  692. UpdateStaticUsage();
  693. UnicodeString KeyFile;
  694. if (Params->FindSwitch(L"PrivateKey", KeyFile))
  695. {
  696. WinConfiguration->DefaultKeyFile = KeyFile;
  697. }
  698. UnicodeString ConsoleVersion;
  699. UnicodeString DotNetVersion;
  700. Params->FindSwitch(L"Console", ConsoleVersion);
  701. Params->FindSwitch(L"DotNet", DotNetVersion);
  702. if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())
  703. {
  704. RecordWrapperVersions(ConsoleVersion, DotNetVersion);
  705. }
  706. if (!DotNetVersion.IsEmpty())
  707. {
  708. Configuration->Usage->Inc(L"ConsoleDotNet");
  709. }
  710. UnicodeString SwitchValue;
  711. if (Params->FindSwitch(L"loglevel", SwitchValue))
  712. {
  713. int StarPos = SwitchValue.Pos(L"*");
  714. if (StarPos > 0)
  715. {
  716. bool LogSensitive = true;
  717. SwitchValue.Delete(StarPos, 1);
  718. if ((StarPos <= SwitchValue.Length()) &&
  719. (SwitchValue[StarPos] == L'-'))
  720. {
  721. LogSensitive = false;
  722. SwitchValue.Delete(StarPos, 1);
  723. }
  724. SwitchValue = SwitchValue.Trim();
  725. Configuration->TemporaryLogSensitive(LogSensitive);
  726. }
  727. int LogProtocol;
  728. if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= -1))
  729. {
  730. Configuration->TemporaryLogProtocol(LogProtocol);
  731. }
  732. }
  733. if (Params->FindSwitch(LOGSIZE_SWITCH, SwitchValue))
  734. {
  735. int StarPos = SwitchValue.Pos(LOGSIZE_SEPARATOR);
  736. int LogMaxCount = 0;
  737. if (StarPos > 1)
  738. {
  739. if (!TryStrToInt(SwitchValue.SubString(1, StarPos - 1), LogMaxCount))
  740. {
  741. LogMaxCount = -1;
  742. }
  743. SwitchValue.Delete(1, StarPos);
  744. SwitchValue = SwitchValue.Trim();
  745. }
  746. __int64 LogMaxSize;
  747. if ((LogMaxCount >= 0) &&
  748. !SwitchValue.IsEmpty() &&
  749. TryStrToSize(SwitchValue, LogMaxSize))
  750. {
  751. Configuration->TemporaryLogMaxCount(LogMaxCount);
  752. Configuration->TemporaryLogMaxSize(LogMaxSize);
  753. }
  754. }
  755. std::unique_ptr<TStrings> RawSettings(new TStringList());
  756. if (Params->FindSwitch(RAWTRANSFERSETTINGS_SWITCH, RawSettings.get()))
  757. {
  758. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings.get(), false));
  759. GUIConfiguration->LoadDefaultCopyParam(OptionsStorage.get());
  760. }
  761. TConsoleMode Mode = cmNone;
  762. if (Params->FindSwitch(L"help") || Params->FindSwitch(L"h") || Params->FindSwitch(L"?"))
  763. {
  764. Mode = cmHelp;
  765. }
  766. else if (Params->FindSwitch(L"batchsettings"))
  767. {
  768. Mode = cmBatchSettings;
  769. }
  770. else if (Params->FindSwitch(KEYGEN_SWITCH))
  771. {
  772. Mode = cmKeyGen;
  773. }
  774. else if (Params->FindSwitch(FINGERPRINTSCAN_SWITCH))
  775. {
  776. Mode = cmFingerprintScan;
  777. }
  778. else if (Params->FindSwitch(DUMPCALLSTACK_SWITCH))
  779. {
  780. Mode = cmDumpCallstack;
  781. }
  782. else if (Params->FindSwitch(INFO_SWITCH))
  783. {
  784. Mode = cmInfo;
  785. }
  786. else if (Params->FindSwitch(COMREGISTRATION_SWITCH))
  787. {
  788. Mode = cmComRegistration;
  789. }
  790. // We have to check for /console only after the other options,
  791. // as the /console is always used when we are run by winscp.com
  792. // (ambiguous use to pass console version)
  793. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(SCRIPT_SWITCH) ||
  794. Params->FindSwitch(COMMAND_SWITCH))
  795. {
  796. Mode = cmScripting;
  797. }
  798. if (Mode != cmNone)
  799. {
  800. return Console(Mode);
  801. }
  802. TTerminalManager * TerminalManager = NULL;
  803. GlyphsModule = NULL;
  804. NonVisualDataModule = NULL;
  805. TStrings * CommandParams = new TStringList;
  806. try
  807. {
  808. TerminalManager = TTerminalManager::Instance();
  809. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  810. try
  811. {
  812. GlyphsModule = new TGlyphsModule(Application);
  813. }
  814. __finally
  815. {
  816. GUIConfiguration->ChangeResourceModule(ResourceModule);
  817. }
  818. NonVisualDataModule = new TNonVisualDataModule(Application);
  819. // The default is 2.5s.
  820. // 20s is used by Office 2010 and Windows 10 Explorer.
  821. // Some applications use an infinite (Thunderbird, Firefox).
  822. // Overriden for some controls using THintInfo.HideTimeout
  823. Application->HintHidePause = 20000;
  824. HintWindowClass = __classid(TScreenTipHintWindow);
  825. UnicodeString IniFileName = Params->SwitchValue(INI_SWITCH);
  826. if (!IniFileName.IsEmpty() && (IniFileName != INI_NUL))
  827. {
  828. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  829. if (!FileExists(ApiPath(IniFileNameExpanded)))
  830. {
  831. // this should be displayed rather at the very beginning.
  832. // however for simplicity (GUI-only), we do it only here.
  833. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  834. }
  835. }
  836. if (Params->FindSwitch(L"UninstallCleanup"))
  837. {
  838. MaintenanceTask();
  839. Configuration->DontSave();
  840. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  841. // workaround is that we create mutex in uninstaller, if it runs silent, and
  842. // ignore the UninstallCleanup, when the mutex exists.
  843. if (OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL)
  844. {
  845. DoCleanupDialogIfAnyDataAndWanted();
  846. }
  847. }
  848. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  849. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  850. {
  851. MaintenanceTask();
  852. if (CheckSafe(Params))
  853. {
  854. RegisterForDefaultProtocols();
  855. Configuration->DontSave();
  856. }
  857. }
  858. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  859. {
  860. MaintenanceTask();
  861. if (CheckSafe(Params))
  862. {
  863. UnregisterForProtocols();
  864. Configuration->DontSave();
  865. }
  866. }
  867. else if (Params->FindSwitch(L"AddSearchPath"))
  868. {
  869. MaintenanceTask();
  870. if (CheckSafe(Params))
  871. {
  872. AddSearchPath(ExtractFilePath(Application->ExeName));
  873. Configuration->DontSave();
  874. }
  875. }
  876. else if (Params->FindSwitch(L"RemoveSearchPath"))
  877. {
  878. MaintenanceTask();
  879. if (CheckSafe(Params))
  880. {
  881. try
  882. {
  883. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  884. }
  885. catch(...)
  886. {
  887. // ignore errors
  888. // (RemoveSearchPath is called always on uninstallation,
  889. // even if AddSearchPath was not used, so we would get the error
  890. // always for non-priviledged user)
  891. }
  892. Configuration->DontSave();
  893. }
  894. }
  895. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  896. {
  897. MaintenanceTask();
  898. ImportSitesIfAny();
  899. }
  900. else if (Params->FindSwitch(L"Usage", SwitchValue))
  901. {
  902. MaintenanceTask();
  903. Usage(SwitchValue);
  904. }
  905. else if (Params->FindSwitch(L"Update"))
  906. {
  907. MaintenanceTask();
  908. CheckForUpdates(false);
  909. }
  910. else if (ShowUpdatesIfAvailable())
  911. {
  912. // noop
  913. }
  914. else if (Params->FindSwitch(L"Exit"))
  915. {
  916. // noop
  917. MaintenanceTask();
  918. Configuration->DontSave();
  919. }
  920. else if (Params->FindSwitch(L"MaintenanceTask"))
  921. {
  922. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  923. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  924. MaintenanceTask();
  925. Configuration->DontSave();
  926. }
  927. else
  928. {
  929. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit, pcRefresh } ParamCommand;
  930. ParamCommand = pcNone;
  931. UnicodeString AutoStartSession;
  932. UnicodeString DownloadFile;
  933. int UseDefaults = -1;
  934. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  935. if (OnlyInstance &&
  936. WinConfiguration->TemporaryDirectoryCleanup)
  937. {
  938. TemporaryDirectoryCleanup();
  939. }
  940. WinConfiguration->CheckDefaultTranslation();
  941. // Loading shell image lists here (rather than only on demand when file controls are being created)
  942. // reduces risk of an occasional crash.
  943. // It seems that the point is to load the lists before any call to SHGetFileInfoWithTimeout.
  944. InitFileControls();
  945. if (!Params->Empty)
  946. {
  947. UnicodeString Value;
  948. if (Params->FindSwitch(DEFAULTS_SWITCH, Value) && CheckSafe(Params))
  949. {
  950. UseDefaults = StrToIntDef(Value, 0);
  951. }
  952. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  953. {
  954. ParamCommand = pcUpload;
  955. if (CommandParams->Count == 0)
  956. {
  957. throw Exception(NO_UPLOAD_LIST_ERROR);
  958. }
  959. }
  960. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  961. {
  962. if (CommandParams->Count > 0)
  963. {
  964. ParamCommand = pcUpload;
  965. }
  966. }
  967. else if (Params->FindSwitch(SYNCHRONIZE_SWITCH, CommandParams, 4))
  968. {
  969. ParamCommand = pcFullSynchronize;
  970. }
  971. else if (Params->FindSwitch(KEEP_UP_TO_DATE_SWITCH, CommandParams, 4))
  972. {
  973. ParamCommand = pcSynchronize;
  974. }
  975. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  976. (CommandParams->Count == 1))
  977. {
  978. ParamCommand = pcEdit;
  979. }
  980. else if (Params->FindSwitch(REFRESH_SWITCH, CommandParams, 1))
  981. {
  982. ParamCommand = pcRefresh;
  983. }
  984. }
  985. if (Params->ParamCount > 0)
  986. {
  987. AutoStartSession = Params->Param[1];
  988. Params->ParamsProcessed(1, 1);
  989. if ((ParamCommand == pcNone) &&
  990. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  991. !Params->FindSwitch(NEWINSTANCE_SWICH) &&
  992. SendToAnotherInstance())
  993. {
  994. Configuration->Usage->Inc(L"SendToAnotherInstance");
  995. return 0;
  996. }
  997. UnicodeString CounterName;
  998. if (Params->FindSwitch(JUMPLIST_SWITCH))
  999. {
  1000. CounterName = L"CommandLineJumpList";
  1001. }
  1002. else if (Params->FindSwitch(DESKTOP_SWITCH))
  1003. {
  1004. CounterName = L"CommandLineDesktop";
  1005. }
  1006. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  1007. {
  1008. CounterName = L"CommandLineSendToHook";
  1009. }
  1010. else
  1011. {
  1012. CounterName = L"CommandLineSession2";
  1013. }
  1014. Configuration->Usage->Inc(CounterName);
  1015. }
  1016. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  1017. {
  1018. AutoStartSession = StoredSessions->Sessions[0]->Name;
  1019. }
  1020. else
  1021. {
  1022. AutoStartSession = WinConfiguration->AutoStartSession;
  1023. }
  1024. if (ParamCommand == pcRefresh)
  1025. {
  1026. Refresh(AutoStartSession, (CommandParams->Count > 0 ? CommandParams->Strings[0] : UnicodeString()));
  1027. return 0;
  1028. }
  1029. // from now flash message boxes on background
  1030. SetOnForeground(false);
  1031. bool NeedSession = (ParamCommand != pcNone);
  1032. bool Retry;
  1033. do
  1034. {
  1035. Retry = false;
  1036. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1037. try
  1038. {
  1039. int Flags = GetCommandLineParseUrlFlags(Params);
  1040. GetLoginData(AutoStartSession, Params, DataList.get(), DownloadFile, NeedSession, NULL, Flags);
  1041. // GetLoginData now Aborts when session is needed and none is selected
  1042. if (DebugAlwaysTrue(!NeedSession || (DataList->Count > 0)))
  1043. {
  1044. if (CheckSafe(Params))
  1045. {
  1046. UnicodeString LogFile;
  1047. if (Params->FindSwitch(LOG_SWITCH, LogFile))
  1048. {
  1049. Configuration->TemporaryLogging(LogFile);
  1050. }
  1051. if (Params->FindSwitch(L"XmlLog", LogFile))
  1052. {
  1053. Configuration->TemporaryActionsLogging(LogFile);
  1054. }
  1055. }
  1056. try
  1057. {
  1058. DebugAssert(!TerminalManager->ActiveTerminal);
  1059. bool CanStart;
  1060. bool Browse = false;
  1061. if (DataList->Count > 0)
  1062. {
  1063. TManagedTerminal * Terminal = TerminalManager->NewTerminals(DataList.get());
  1064. UnicodeString BrowseFile;
  1065. if (Params->FindSwitch(BROWSE_SWITCH, BrowseFile) &&
  1066. (!BrowseFile.IsEmpty() || !DownloadFile.IsEmpty()))
  1067. {
  1068. if (BrowseFile.IsEmpty())
  1069. {
  1070. BrowseFile = DownloadFile;
  1071. }
  1072. DebugAssert(Terminal->RemoteExplorerState == NULL);
  1073. Terminal->RemoteExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);
  1074. DebugAssert(Terminal->LocalExplorerState == NULL);
  1075. Terminal->LocalExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);
  1076. DownloadFile = UnicodeString();
  1077. Browse = true;
  1078. }
  1079. if (!DownloadFile.IsEmpty())
  1080. {
  1081. Terminal->AutoReadDirectory = false;
  1082. DownloadFile = UnixIncludeTrailingBackslash(Terminal->SessionData->RemoteDirectory) + DownloadFile;
  1083. Terminal->SessionData->RemoteDirectory = L"";
  1084. Terminal->StateData->RemoteDirectory = Terminal->SessionData->RemoteDirectory;
  1085. }
  1086. TerminalManager->ActiveTerminal = Terminal;
  1087. CanStart = (TerminalManager->Count > 0);
  1088. }
  1089. else
  1090. {
  1091. DebugAssert(!NeedSession);
  1092. CanStart = true;
  1093. }
  1094. if (!CanStart)
  1095. {
  1096. // do not prompt with login dialog, if connection of
  1097. // auto-start session (typically from command line) failed
  1098. if (AutoStartSession.IsEmpty())
  1099. {
  1100. Retry = true;
  1101. }
  1102. }
  1103. else
  1104. {
  1105. // from now on, we do not support runtime interface change
  1106. CustomWinConfiguration->CanApplyInterfaceImmediately = false;
  1107. TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();
  1108. CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;
  1109. try
  1110. {
  1111. // moved inside try .. __finally, because it can fail as well
  1112. TerminalManager->ScpExplorer = ScpExplorer;
  1113. if ((ParamCommand != pcNone) || !DownloadFile.IsEmpty())
  1114. {
  1115. Configuration->Usage->Inc(L"CommandLineOperation");
  1116. ScpExplorer->StandaloneOperation = true;
  1117. }
  1118. if (ParamCommand == pcUpload)
  1119. {
  1120. Upload(TerminalManager->ActiveTerminal, CommandParams, UseDefaults);
  1121. }
  1122. else if (ParamCommand == pcFullSynchronize)
  1123. {
  1124. FullSynchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  1125. CommandParams, UseDefaults);
  1126. }
  1127. else if (ParamCommand == pcSynchronize)
  1128. {
  1129. Synchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  1130. CommandParams, UseDefaults);
  1131. }
  1132. else if (ParamCommand == pcEdit)
  1133. {
  1134. Edit(ScpExplorer, CommandParams);
  1135. }
  1136. else if (!DownloadFile.IsEmpty())
  1137. {
  1138. Download(TerminalManager->ActiveTerminal, DownloadFile,
  1139. UseDefaults);
  1140. }
  1141. else
  1142. {
  1143. if (DataList->Count == 0)
  1144. {
  1145. LifetimeRuns = Configuration->Usage->Inc(L"RunsNormal");
  1146. }
  1147. }
  1148. ScpExplorer->StandaloneOperation = false;
  1149. if (Browse)
  1150. {
  1151. ScpExplorer->BrowseFile();
  1152. }
  1153. Application->Run();
  1154. // to allow dialog boxes show later (like from CheckConfigurationForceSave)
  1155. SetAppTerminated(False);
  1156. }
  1157. __finally
  1158. {
  1159. TerminalManager->ScpExplorer = NULL;
  1160. SAFE_DESTROY(ScpExplorer);
  1161. }
  1162. }
  1163. }
  1164. catch (Exception &E)
  1165. {
  1166. ShowExtendedException(&E);
  1167. }
  1168. }
  1169. }
  1170. // Catch EAbort from Synchronize() and similar functions, so that CheckConfigurationForceSave is processed
  1171. catch (EAbort & E)
  1172. {
  1173. Retry = false; // unlikely to be true, but just in case
  1174. }
  1175. }
  1176. while (Retry);
  1177. }
  1178. // In GUI mode only
  1179. CheckConfigurationForceSave();
  1180. }
  1181. __finally
  1182. {
  1183. delete NonVisualDataModule;
  1184. NonVisualDataModule = NULL;
  1185. ReleaseImagesModules();
  1186. delete GlyphsModule;
  1187. GlyphsModule = NULL;
  1188. TTerminalManager::DestroyInstance();
  1189. delete CommandParams;
  1190. }
  1191. return 0;
  1192. }