WinMain.cpp 40 KB

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