WinMain.cpp 42 KB

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