WinMain.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  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 then 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 InterfaceStarted()
  376. {
  377. // deliberate downcast
  378. int StartupSeconds = static_cast<int>(SecondsBetween(Now(), Started));
  379. if (LifetimeRuns > 0)
  380. {
  381. if (LifetimeRuns == 1)
  382. {
  383. Configuration->Usage->Set(L"StartupSeconds1", StartupSeconds);
  384. }
  385. else if (LifetimeRuns == 2)
  386. {
  387. Configuration->Usage->Set(L"StartupSeconds2", StartupSeconds);
  388. }
  389. Configuration->Usage->Set(L"StartupSecondsLast", StartupSeconds);
  390. }
  391. }
  392. //---------------------------------------------------------------------------
  393. void __fastcall UpdateStaticUsage()
  394. {
  395. LifetimeRuns = Configuration->Usage->Inc(L"Runs");
  396. Configuration->Usage->UpdateCurrentVersion();
  397. Configuration->Usage->Set(L"WindowsVersion", (WindowsVersionLong()));
  398. Configuration->Usage->Set(L"WindowsProductName", (WindowsProductName()));
  399. DWORD Type;
  400. GetWindowsProductType(Type);
  401. Configuration->Usage->Set(L"WindowsProductType", (static_cast<int>(Type)));
  402. Configuration->Usage->Set(L"Windows64", IsWin64());
  403. Configuration->Usage->Set(L"UWP", IsUWP());
  404. Configuration->Usage->Set(L"DefaultLocale",
  405. // See TGUIConfiguration::GetAppliedLocaleHex()
  406. IntToHex(static_cast<int>(GetDefaultLCID()), 4));
  407. Configuration->Usage->Set(L"Locale", WinConfiguration->AppliedLocaleHex);
  408. Configuration->Usage->Set(L"EncodingMultiByteAnsi", !TEncoding::Default->IsSingleByte);
  409. Configuration->Usage->Set(L"PixelsPerInch", Screen->PixelsPerInch);
  410. bool PixelsPerInchSystemDiffers = false;
  411. bool PixelsPerInchMonitorsDiffer = false;
  412. bool PixelsPerInchAxesDiffer = false;
  413. HINSTANCE ShCoreLibrary = LoadLibrary(L"shcore.dll");
  414. if (ShCoreLibrary != NULL)
  415. {
  416. GetDpiForMonitorProc GetDpiForMonitor =
  417. (GetDpiForMonitorProc)GetProcAddress(ShCoreLibrary, "GetDpiForMonitor");
  418. if (GetDpiForMonitor != NULL)
  419. {
  420. unsigned int PrimaryDpiX;
  421. unsigned int PrimaryDpiY;
  422. for (int Index = 0; Index < Screen->MonitorCount; Index++)
  423. {
  424. unsigned int DpiX;
  425. unsigned int DpiY;
  426. GetDpiForMonitor(Screen->Monitors[Index]->Handle, MDT_Default, &DpiX, &DpiY);
  427. if (DpiX != DpiY)
  428. {
  429. PixelsPerInchAxesDiffer = true;
  430. }
  431. if (Index == 0)
  432. {
  433. PrimaryDpiX = DpiX;
  434. PrimaryDpiY = DpiY;
  435. // PixelsPerInch is GetDeviceCaps(DC, LOGPIXELSY)
  436. if (DpiY != (unsigned int)Screen->PixelsPerInch)
  437. {
  438. PixelsPerInchSystemDiffers = true;
  439. }
  440. }
  441. else
  442. {
  443. if ((DpiX != PrimaryDpiX) ||
  444. (DpiY != PrimaryDpiY))
  445. {
  446. PixelsPerInchMonitorsDiffer = true;
  447. }
  448. }
  449. }
  450. }
  451. }
  452. if (PixelsPerInchSystemDiffers)
  453. {
  454. Configuration->Usage->Inc(L"PixelsPerInchSystemDiffered");
  455. }
  456. Configuration->Usage->Set(L"PixelsPerInchMonitorsDiffer", PixelsPerInchMonitorsDiffer);
  457. Configuration->Usage->Set(L"PixelsPerInchAxesDiffer", PixelsPerInchAxesDiffer);
  458. Configuration->Usage->Set(L"WorkAreaWidth", Screen->WorkAreaWidth);
  459. Configuration->Usage->Set(L"WorkAreaHeight", Screen->WorkAreaHeight);
  460. HDC DC = GetDC(NULL);
  461. int Planes = GetDeviceCaps(DC, PLANES);
  462. int BitsPixel = GetDeviceCaps(DC, BITSPIXEL);
  463. Configuration->Usage->Set(L"ColorDepth", Planes * BitsPixel);
  464. Configuration->Usage->Set(L"MonitorCount", Screen->MonitorCount);
  465. Configuration->Usage->Set(L"NotUseThemes", !UseThemes());
  466. Configuration->Usage->Set(L"ThemeDefaultFontSize", Application->DefaultFont->Size);
  467. Configuration->Usage->Set(L"ThemeIconFontSize", Screen->IconFont->Size);
  468. Configuration->Usage->Set(L"SysColorWindow", ColorToRGBStr(clWindow));
  469. Configuration->Usage->Set(L"SysColorBtnFace", ColorToRGBStr(clBtnFace));
  470. Configuration->Usage->Set(L"SysColorWindowText", ColorToRGBStr(clWindowText));
  471. UnicodeString ProgramsFolder;
  472. ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);
  473. ProgramsFolder = IncludeTrailingBackslash(ExpandFileName(ProgramsFolder));
  474. UnicodeString ExeName = ExpandFileName(Application->ExeName);
  475. bool InProgramFiles = AnsiSameText(ExeName.SubString(1, ProgramsFolder.Length()), ProgramsFolder);
  476. Configuration->Usage->Set(L"InProgramFiles", InProgramFiles);
  477. Configuration->Usage->Set(L"IsInstalled", IsInstalled());
  478. Configuration->Usage->Set(L"Wine", IsWine());
  479. Configuration->Usage->Set(L"NetFrameworkVersion", GetNetVersionStr());
  480. Configuration->Usage->Set(L"PowerShellVersion", GetPowerShellVersionStr());
  481. UnicodeString ParentProcess = GetAncestorProcessName();
  482. // do not record the installer as a parent process
  483. if (!ParentProcess.IsEmpty() &&
  484. (!StartsText(L"winscp-", ParentProcess) || !EndsText(L"-setup", ParentProcess)))
  485. {
  486. UnicodeString ParentProcesses = Configuration->Usage->Get(L"ParentProcesses");
  487. std::unique_ptr<TStringList> ParentProcessesList(CreateSortedStringList());
  488. ParentProcessesList->CommaText = ParentProcesses;
  489. ParentProcessesList->Add(ParentProcess.LowerCase());
  490. Configuration->Usage->Set(L"ParentProcesses", ParentProcessesList->CommaText);
  491. }
  492. WinConfiguration->UpdateStaticUsage();
  493. }
  494. //---------------------------------------------------------------------------
  495. void __fastcall MaintenanceTask()
  496. {
  497. CoreMaintenanceTask();
  498. }
  499. //---------------------------------------------------------------------------
  500. typedef std::vector<HWND> THandles;
  501. typedef std::map<unsigned long, THandles> TProcesses;
  502. //---------------------------------------------------------------------------
  503. BOOL __stdcall EnumOtherInstances(HWND Handle, LPARAM AParam)
  504. {
  505. TProcesses & Processes = *reinterpret_cast<TProcesses *>(AParam);
  506. unsigned long ProcessId;
  507. if (GetWindowThreadProcessId(Handle, &ProcessId) != 0)
  508. {
  509. Processes[ProcessId].push_back(Handle);
  510. }
  511. return TRUE;
  512. }
  513. //---------------------------------------------------------------------------
  514. static bool __fastcall SendCopyDataMessage(HWND Window, TCopyDataMessage & Message)
  515. {
  516. COPYDATASTRUCT CopyData;
  517. CopyData.cbData = sizeof(Message);
  518. CopyData.lpData = &Message;
  519. LRESULT SendResult =
  520. SendMessage(Window, WM_COPYDATA,
  521. reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));
  522. bool Result = (SendResult > 0);
  523. return Result;
  524. }
  525. //---------------------------------------------------------------------------
  526. static void __fastcall FindOtherInstances(THandles & OtherInstances)
  527. {
  528. TProcesses Processes;
  529. // FindWindow is optimization (if there's no hidden window, no point enumerating all windows to find some)
  530. if ((FindWindow(HIDDEN_WINDOW_NAME, NULL) != NULL) &&
  531. EnumWindows(EnumOtherInstances, reinterpret_cast<LPARAM>(&Processes)))
  532. {
  533. TCopyDataMessage Message;
  534. Message.Command = TCopyDataMessage::MainWindowCheck;
  535. TProcesses::const_iterator ProcessI = Processes.begin();
  536. while (ProcessI != Processes.end())
  537. {
  538. HWND HiddenWindow = NULL;
  539. THandles::const_iterator WindowI = ProcessI->second.begin();
  540. while ((HiddenWindow == NULL) && (WindowI != ProcessI->second.end()))
  541. {
  542. wchar_t ClassName[1024];
  543. if (GetClassName(*WindowI, ClassName, LENOF(ClassName)) != 0)
  544. {
  545. NULL_TERMINATE(ClassName);
  546. if (wcscmp(ClassName, HIDDEN_WINDOW_NAME) == 0)
  547. {
  548. HiddenWindow = *WindowI;
  549. }
  550. }
  551. WindowI++;
  552. }
  553. if (HiddenWindow != NULL)
  554. {
  555. WindowI = ProcessI->second.begin();
  556. while (WindowI != ProcessI->second.end())
  557. {
  558. if (*WindowI != HiddenWindow) // optimization
  559. {
  560. if (SendCopyDataMessage(*WindowI, Message))
  561. {
  562. OtherInstances.push_back(*WindowI);
  563. break;
  564. }
  565. }
  566. WindowI++;
  567. }
  568. }
  569. ProcessI++;
  570. }
  571. }
  572. }
  573. //---------------------------------------------------------------------------
  574. bool __fastcall SendToAnotherInstance()
  575. {
  576. THandles OtherInstances;
  577. FindOtherInstances(OtherInstances);
  578. bool Result = false;
  579. THandles::const_iterator I = OtherInstances.begin();
  580. while (!Result && (I != OtherInstances.end()))
  581. {
  582. HWND Handle = *I;
  583. TCopyDataMessage Message;
  584. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  585. if (SendCopyDataMessage(Handle, Message))
  586. {
  587. // Restore window, if minimized
  588. ShowWindow(Handle, SW_RESTORE);
  589. // bring it to foreground
  590. SetForegroundWindow(Handle);
  591. Message.Command = TCopyDataMessage::CommandCommandLine;
  592. wcsncpy(Message.CommandLine, CmdLine, LENOF(Message.CommandLine));
  593. NULL_TERMINATE(Message.CommandLine);
  594. Result = SendCopyDataMessage(Handle, Message);
  595. }
  596. I++;
  597. }
  598. return Result;
  599. }
  600. //---------------------------------------------------------------------------
  601. void __fastcall Refresh(const UnicodeString & Session, const UnicodeString & Path)
  602. {
  603. THandles OtherInstances;
  604. FindOtherInstances(OtherInstances);
  605. THandles::const_iterator I = OtherInstances.begin();
  606. while (I != OtherInstances.end())
  607. {
  608. HWND Handle = *I;
  609. TCopyDataMessage Message;
  610. Message.Command = TCopyDataMessage::RefreshPanel;
  611. wcsncpy(Message.Refresh.Session, Session.c_str(), LENOF(Message.Refresh.Session));
  612. NULL_TERMINATE(Message.Refresh.Session);
  613. wcsncpy(Message.Refresh.Path, Path.c_str(), LENOF(Message.Refresh.Path));
  614. NULL_TERMINATE(Message.Refresh.Path);
  615. SendCopyDataMessage(Handle, Message);
  616. I++;
  617. }
  618. }
  619. //---------------------------------------------------------------------------
  620. bool __fastcall ShowUpdatesIfAvailable()
  621. {
  622. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  623. int CurrentCompoundVer = Configuration->CompoundVersion;
  624. bool NoPopup = true;
  625. bool Result =
  626. !IsUWP() &&
  627. Updates.ShowOnStartup &&
  628. Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&
  629. !Updates.Results.Disabled &&
  630. ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&
  631. !Updates.ShownResults;
  632. if (Result)
  633. {
  634. Configuration->Usage->Inc(L"UpdateStartup");
  635. Result = CheckForUpdates(true);
  636. if (Result)
  637. {
  638. Configuration->Usage->Inc(L"UpdateDownloadOpensStartup");
  639. }
  640. NoPopup = false;
  641. }
  642. else if (WinConfiguration->ShowTips)
  643. {
  644. int Days = DaysBetween(WinConfiguration->TipsShown, Now());
  645. if ((Days >= Updates.Results.TipsIntervalDays) &&
  646. (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))
  647. {
  648. UnicodeString Tip = FirstUnshownTip();
  649. if (!Tip.IsEmpty())
  650. {
  651. AutoShowNewTip();
  652. NoPopup = false;
  653. }
  654. else
  655. {
  656. Configuration->Usage->Inc(L"TipsNoUnseen");
  657. }
  658. }
  659. }
  660. if (NoPopup)
  661. {
  662. WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;
  663. }
  664. return Result;
  665. }
  666. //---------------------------------------------------------------------------
  667. int __fastcall Execute()
  668. {
  669. DebugAssert(StoredSessions);
  670. TProgramParams * Params = TProgramParams::Instance();
  671. DebugAssert(Params);
  672. // do not flash message boxes on startup
  673. SetOnForeground(true);
  674. // let installer know, that some instance of application is running
  675. CreateMutex(NULL, False, AppName.c_str());
  676. bool OnlyInstance = (GetLastError() == 0);
  677. UpdateStaticUsage();
  678. UnicodeString KeyFile;
  679. if (Params->FindSwitch(L"PrivateKey", KeyFile))
  680. {
  681. WinConfiguration->DefaultKeyFile = KeyFile;
  682. }
  683. UnicodeString ConsoleVersion;
  684. UnicodeString DotNetVersion;
  685. Params->FindSwitch(L"Console", ConsoleVersion);
  686. Params->FindSwitch(L"DotNet", DotNetVersion);
  687. if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())
  688. {
  689. RecordWrapperVersions(ConsoleVersion, DotNetVersion);
  690. }
  691. if (!DotNetVersion.IsEmpty())
  692. {
  693. Configuration->Usage->Inc(L"ConsoleDotNet");
  694. }
  695. UnicodeString SwitchValue;
  696. if (Params->FindSwitch(L"loglevel", SwitchValue))
  697. {
  698. int StarPos = SwitchValue.Pos(L"*");
  699. if (StarPos > 0)
  700. {
  701. bool LogSensitive = true;
  702. SwitchValue.Delete(StarPos, 1);
  703. if ((StarPos <= SwitchValue.Length()) &&
  704. (SwitchValue[StarPos] == L'-'))
  705. {
  706. LogSensitive = false;
  707. SwitchValue.Delete(StarPos, 1);
  708. }
  709. SwitchValue = SwitchValue.Trim();
  710. Configuration->TemporaryLogSensitive(LogSensitive);
  711. }
  712. int LogProtocol;
  713. if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= -1))
  714. {
  715. Configuration->TemporaryLogProtocol(LogProtocol);
  716. }
  717. }
  718. if (Params->FindSwitch(LOGSIZE_SWITCH, SwitchValue))
  719. {
  720. int StarPos = SwitchValue.Pos(LOGSIZE_SEPARATOR);
  721. int LogMaxCount = 0;
  722. if (StarPos > 1)
  723. {
  724. if (!TryStrToInt(SwitchValue.SubString(1, StarPos - 1), LogMaxCount))
  725. {
  726. LogMaxCount = -1;
  727. }
  728. SwitchValue.Delete(1, StarPos);
  729. SwitchValue = SwitchValue.Trim();
  730. }
  731. __int64 LogMaxSize;
  732. if ((LogMaxCount >= 0) &&
  733. !SwitchValue.IsEmpty() &&
  734. TryStrToSize(SwitchValue, LogMaxSize))
  735. {
  736. Configuration->TemporaryLogMaxCount(LogMaxCount);
  737. Configuration->TemporaryLogMaxSize(LogMaxSize);
  738. }
  739. }
  740. std::unique_ptr<TStrings> RawSettings(new TStringList());
  741. if (Params->FindSwitch(RAWTRANSFERSETTINGS_SWITCH, RawSettings.get()))
  742. {
  743. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings.get(), false));
  744. GUIConfiguration->LoadDefaultCopyParam(OptionsStorage.get());
  745. }
  746. TConsoleMode Mode = cmNone;
  747. if (Params->FindSwitch(L"help") || Params->FindSwitch(L"h") || Params->FindSwitch(L"?"))
  748. {
  749. Mode = cmHelp;
  750. }
  751. else if (Params->FindSwitch(L"batchsettings"))
  752. {
  753. Mode = cmBatchSettings;
  754. }
  755. else if (Params->FindSwitch(KEYGEN_SWITCH))
  756. {
  757. Mode = cmKeyGen;
  758. }
  759. else if (Params->FindSwitch(FINGERPRINTSCAN_SWITCH))
  760. {
  761. Mode = cmFingerprintScan;
  762. }
  763. else if (Params->FindSwitch(DUMPCALLSTACK_SWITCH))
  764. {
  765. Mode = cmDumpCallstack;
  766. }
  767. else if (Params->FindSwitch(INFO_SWITCH))
  768. {
  769. Mode = cmInfo;
  770. }
  771. else if (Params->FindSwitch(COMREGISTRATION_SWITCH))
  772. {
  773. Mode = cmComRegistration;
  774. }
  775. // We have to check for /console only after the other options,
  776. // as the /console is always used when we are run by winscp.com
  777. // (ambiguous use to pass console version)
  778. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(SCRIPT_SWITCH) ||
  779. Params->FindSwitch(COMMAND_SWITCH))
  780. {
  781. Mode = cmScripting;
  782. }
  783. if (Mode != cmNone)
  784. {
  785. return Console(Mode);
  786. }
  787. TTerminalManager * TerminalManager = NULL;
  788. GlyphsModule = NULL;
  789. NonVisualDataModule = NULL;
  790. TStrings * CommandParams = new TStringList;
  791. try
  792. {
  793. TerminalManager = TTerminalManager::Instance();
  794. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  795. try
  796. {
  797. GlyphsModule = new TGlyphsModule(Application);
  798. }
  799. __finally
  800. {
  801. GUIConfiguration->ChangeResourceModule(ResourceModule);
  802. }
  803. NonVisualDataModule = new TNonVisualDataModule(Application);
  804. // The default is 2.5s.
  805. // 20s is used by Office 2010 and Windows 10 Explorer.
  806. // Some applications use an infinite (Thunderbird, Firefox).
  807. // Overriden for some controls using THintInfo.HideTimeout
  808. Application->HintHidePause = 20000;
  809. HintWindowClass = __classid(TScreenTipHintWindow);
  810. UnicodeString IniFileName = Params->SwitchValue(INI_SWITCH);
  811. if (!IniFileName.IsEmpty() && (IniFileName != INI_NUL))
  812. {
  813. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  814. if (!FileExists(ApiPath(IniFileNameExpanded)))
  815. {
  816. // this should be displayed rather at the very beginning.
  817. // however for simplicity (GUI-only), we do it only here.
  818. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  819. }
  820. }
  821. if (Params->FindSwitch(L"UninstallCleanup"))
  822. {
  823. MaintenanceTask();
  824. Configuration->DontSave();
  825. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  826. // workaround is that we create mutex in uninstaller, if it runs silent, and
  827. // ignore the UninstallCleanup, when the mutex exists.
  828. if (OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL)
  829. {
  830. DoCleanupDialogIfAnyDataAndWanted();
  831. }
  832. }
  833. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  834. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  835. {
  836. MaintenanceTask();
  837. if (CheckSafe(Params))
  838. {
  839. RegisterForDefaultProtocols();
  840. Configuration->DontSave();
  841. }
  842. }
  843. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  844. {
  845. MaintenanceTask();
  846. if (CheckSafe(Params))
  847. {
  848. UnregisterForProtocols();
  849. Configuration->DontSave();
  850. }
  851. }
  852. else if (Params->FindSwitch(L"AddSearchPath"))
  853. {
  854. MaintenanceTask();
  855. if (CheckSafe(Params))
  856. {
  857. AddSearchPath(ExtractFilePath(Application->ExeName));
  858. Configuration->DontSave();
  859. }
  860. }
  861. else if (Params->FindSwitch(L"RemoveSearchPath"))
  862. {
  863. MaintenanceTask();
  864. if (CheckSafe(Params))
  865. {
  866. try
  867. {
  868. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  869. }
  870. catch(...)
  871. {
  872. // ignore errors
  873. // (RemoveSearchPath is called always on uninstallation,
  874. // even if AddSearchPath was not used, so we would get the error
  875. // always for non-priviledged user)
  876. }
  877. Configuration->DontSave();
  878. }
  879. }
  880. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  881. {
  882. MaintenanceTask();
  883. ImportSitesIfAny();
  884. }
  885. else if (Params->FindSwitch(L"Usage", SwitchValue))
  886. {
  887. MaintenanceTask();
  888. Usage(SwitchValue);
  889. }
  890. else if (Params->FindSwitch(L"Update"))
  891. {
  892. MaintenanceTask();
  893. CheckForUpdates(false);
  894. }
  895. else if (ShowUpdatesIfAvailable())
  896. {
  897. // noop
  898. }
  899. else if (Params->FindSwitch(L"Exit"))
  900. {
  901. // noop
  902. MaintenanceTask();
  903. Configuration->DontSave();
  904. }
  905. else if (Params->FindSwitch(L"MaintenanceTask"))
  906. {
  907. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  908. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  909. MaintenanceTask();
  910. Configuration->DontSave();
  911. }
  912. else
  913. {
  914. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit, pcRefresh } ParamCommand;
  915. ParamCommand = pcNone;
  916. UnicodeString AutoStartSession;
  917. UnicodeString DownloadFile;
  918. int UseDefaults = -1;
  919. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  920. if (OnlyInstance &&
  921. WinConfiguration->TemporaryDirectoryCleanup)
  922. {
  923. TemporaryDirectoryCleanup();
  924. }
  925. WinConfiguration->CheckDefaultTranslation();
  926. // Loading shell image lists here (rather than only on demand when file controls are being created)
  927. // reduces risk of an occasional crash.
  928. // It seems that the point is to load the lists before any call to SHGetFileInfoWithTimeout.
  929. InitFileControls();
  930. if (!Params->Empty)
  931. {
  932. UnicodeString Value;
  933. if (Params->FindSwitch(DEFAULTS_SWITCH, Value) && CheckSafe(Params))
  934. {
  935. UseDefaults = StrToIntDef(Value, 0);
  936. }
  937. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  938. {
  939. ParamCommand = pcUpload;
  940. if (CommandParams->Count == 0)
  941. {
  942. throw Exception(NO_UPLOAD_LIST_ERROR);
  943. }
  944. }
  945. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  946. {
  947. if (CommandParams->Count > 0)
  948. {
  949. ParamCommand = pcUpload;
  950. }
  951. }
  952. else if (Params->FindSwitch(SYNCHRONIZE_SWITCH, CommandParams, 4))
  953. {
  954. ParamCommand = pcFullSynchronize;
  955. }
  956. else if (Params->FindSwitch(KEEP_UP_TO_DATE_SWITCH, CommandParams, 4))
  957. {
  958. ParamCommand = pcSynchronize;
  959. }
  960. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  961. (CommandParams->Count == 1))
  962. {
  963. ParamCommand = pcEdit;
  964. }
  965. else if (Params->FindSwitch(REFRESH_SWITCH, CommandParams, 1))
  966. {
  967. ParamCommand = pcRefresh;
  968. }
  969. }
  970. if (Params->ParamCount > 0)
  971. {
  972. AutoStartSession = Params->Param[1];
  973. Params->ParamsProcessed(1, 1);
  974. if ((ParamCommand == pcNone) &&
  975. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  976. !Params->FindSwitch(NEWINSTANCE_SWICH) &&
  977. SendToAnotherInstance())
  978. {
  979. Configuration->Usage->Inc(L"SendToAnotherInstance");
  980. return 0;
  981. }
  982. UnicodeString CounterName;
  983. if (Params->FindSwitch(JUMPLIST_SWITCH))
  984. {
  985. CounterName = L"CommandLineJumpList";
  986. }
  987. else if (Params->FindSwitch(DESKTOP_SWITCH))
  988. {
  989. CounterName = L"CommandLineDesktop";
  990. }
  991. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  992. {
  993. CounterName = L"CommandLineSendToHook";
  994. }
  995. else
  996. {
  997. CounterName = L"CommandLineSession2";
  998. }
  999. Configuration->Usage->Inc(CounterName);
  1000. }
  1001. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  1002. {
  1003. AutoStartSession = StoredSessions->Sessions[0]->Name;
  1004. }
  1005. else
  1006. {
  1007. AutoStartSession = WinConfiguration->AutoStartSession;
  1008. }
  1009. if (ParamCommand == pcRefresh)
  1010. {
  1011. Refresh(AutoStartSession, (CommandParams->Count > 0 ? CommandParams->Strings[0] : UnicodeString()));
  1012. return 0;
  1013. }
  1014. // from now flash message boxes on background
  1015. SetOnForeground(false);
  1016. bool NeedSession = (ParamCommand != pcNone);
  1017. bool Retry;
  1018. do
  1019. {
  1020. Retry = false;
  1021. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1022. try
  1023. {
  1024. GetLoginData(AutoStartSession, Params, DataList.get(), DownloadFile, NeedSession, NULL, pufAllowStoredSiteWithProtocol);
  1025. // GetLoginData now Aborts when session is needed and none is selected
  1026. if (DebugAlwaysTrue(!NeedSession || (DataList->Count > 0)))
  1027. {
  1028. if (CheckSafe(Params))
  1029. {
  1030. UnicodeString LogFile;
  1031. if (Params->FindSwitch(LOG_SWITCH, LogFile))
  1032. {
  1033. Configuration->TemporaryLogging(LogFile);
  1034. }
  1035. if (Params->FindSwitch(L"XmlLog", LogFile))
  1036. {
  1037. Configuration->TemporaryActionsLogging(LogFile);
  1038. }
  1039. }
  1040. try
  1041. {
  1042. DebugAssert(!TerminalManager->ActiveTerminal);
  1043. bool CanStart;
  1044. bool Browse = false;
  1045. if (DataList->Count > 0)
  1046. {
  1047. TManagedTerminal * Terminal = TerminalManager->NewTerminals(DataList.get());
  1048. UnicodeString BrowseFile;
  1049. if (Params->FindSwitch(BROWSE_SWITCH, BrowseFile) &&
  1050. (!BrowseFile.IsEmpty() || !DownloadFile.IsEmpty()))
  1051. {
  1052. if (BrowseFile.IsEmpty())
  1053. {
  1054. BrowseFile = DownloadFile;
  1055. }
  1056. DebugAssert(Terminal->RemoteExplorerState == NULL);
  1057. Terminal->RemoteExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);
  1058. DebugAssert(Terminal->LocalExplorerState == NULL);
  1059. Terminal->LocalExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);
  1060. DownloadFile = UnicodeString();
  1061. Browse = true;
  1062. }
  1063. if (!DownloadFile.IsEmpty())
  1064. {
  1065. Terminal->AutoReadDirectory = false;
  1066. DownloadFile = UnixIncludeTrailingBackslash(Terminal->SessionData->RemoteDirectory) + DownloadFile;
  1067. Terminal->SessionData->RemoteDirectory = L"";
  1068. Terminal->StateData->RemoteDirectory = Terminal->SessionData->RemoteDirectory;
  1069. }
  1070. TerminalManager->ActiveTerminal = Terminal;
  1071. CanStart = (TerminalManager->Count > 0);
  1072. }
  1073. else
  1074. {
  1075. DebugAssert(!NeedSession);
  1076. CanStart = true;
  1077. }
  1078. if (!CanStart)
  1079. {
  1080. // do not prompt with login dialog, if connection of
  1081. // auto-start session (typically from command line) failed
  1082. if (AutoStartSession.IsEmpty())
  1083. {
  1084. Retry = true;
  1085. }
  1086. }
  1087. else
  1088. {
  1089. // from now on, we do not support runtime interface change
  1090. CustomWinConfiguration->CanApplyInterfaceImmediately = false;
  1091. TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();
  1092. CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;
  1093. try
  1094. {
  1095. // moved inside try .. __finally, because it can fail as well
  1096. TerminalManager->ScpExplorer = ScpExplorer;
  1097. if ((ParamCommand != pcNone) || !DownloadFile.IsEmpty())
  1098. {
  1099. Configuration->Usage->Inc(L"CommandLineOperation");
  1100. }
  1101. if (ParamCommand == pcUpload)
  1102. {
  1103. Upload(TerminalManager->ActiveTerminal, CommandParams, UseDefaults);
  1104. }
  1105. else if (ParamCommand == pcFullSynchronize)
  1106. {
  1107. FullSynchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  1108. CommandParams, UseDefaults);
  1109. }
  1110. else if (ParamCommand == pcSynchronize)
  1111. {
  1112. Synchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  1113. CommandParams, UseDefaults);
  1114. }
  1115. else if (ParamCommand == pcEdit)
  1116. {
  1117. Edit(ScpExplorer, CommandParams);
  1118. }
  1119. else if (!DownloadFile.IsEmpty())
  1120. {
  1121. Download(TerminalManager->ActiveTerminal, DownloadFile,
  1122. UseDefaults);
  1123. }
  1124. if (Browse)
  1125. {
  1126. ScpExplorer->BrowseFile();
  1127. }
  1128. Application->Run();
  1129. // to allow dialog boxes show later (like from CheckConfigurationForceSave)
  1130. SetAppTerminated(False);
  1131. }
  1132. __finally
  1133. {
  1134. TerminalManager->ScpExplorer = NULL;
  1135. SAFE_DESTROY(ScpExplorer);
  1136. }
  1137. }
  1138. }
  1139. catch (Exception &E)
  1140. {
  1141. ShowExtendedException(&E);
  1142. }
  1143. }
  1144. }
  1145. // Catch EAbort from Synchronize() and similar functions, so that CheckConfigurationForceSave is processed
  1146. catch (EAbort & E)
  1147. {
  1148. Retry = false; // unlikely to be true, but just in case
  1149. }
  1150. }
  1151. while (Retry);
  1152. }
  1153. // In GUI mode only
  1154. CheckConfigurationForceSave();
  1155. }
  1156. __finally
  1157. {
  1158. delete NonVisualDataModule;
  1159. NonVisualDataModule = NULL;
  1160. ReleaseImagesModules();
  1161. delete GlyphsModule;
  1162. GlyphsModule = NULL;
  1163. TTerminalManager::DestroyInstance();
  1164. delete CommandParams;
  1165. }
  1166. return 0;
  1167. }