WinMain.cpp 42 KB

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