WinMain.cpp 42 KB

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