WinMain.cpp 43 KB

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