WinMain.cpp 40 KB

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