WinMain.cpp 43 KB

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