WinMain.cpp 43 KB

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