WinMain.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <CoreMain.h>
  5. #include <Log.h>
  6. #include <TextsWin.h>
  7. #include <TextsCore.h>
  8. #include <HelpWin.h>
  9. #include "CustomScpExplorer.h"
  10. #include "TerminalManager.h"
  11. #include "NonVisual.h"
  12. #include "Glyphs.h"
  13. #include "ProgParams.h"
  14. #include "Setup.h"
  15. #include "WinConfiguration.h"
  16. #include "GUITools.h"
  17. #include "Tools.h"
  18. #include "WinApi.h"
  19. #include <DateUtils.hpp>
  20. //---------------------------------------------------------------------------
  21. #pragma package(smart_init)
  22. //---------------------------------------------------------------------------
  23. void __fastcall GetLoginData(UnicodeString SessionName, TOptions * Options,
  24. TObjectList * DataList, UnicodeString & DownloadFile, bool NeedSession)
  25. {
  26. bool DefaultsOnly = false;
  27. if (StoredSessions->IsFolder(SessionName) ||
  28. StoredSessions->IsWorkspace(SessionName))
  29. {
  30. StoredSessions->GetFolderOrWorkspace(SessionName, DataList);
  31. }
  32. else
  33. {
  34. TSessionData * SessionData =
  35. StoredSessions->ParseUrl(SessionName, Options, DefaultsOnly,
  36. &DownloadFile);
  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. Abort();
  59. }
  60. }
  61. }
  62. if (DefaultsOnly && !NeedSession)
  63. {
  64. // No URL specified on command-line and no explicit command-line parameter
  65. // that results 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. DebugAssert(DataList->Count <= 1);
  76. if (!DoLoginDialog(StoredSessions, DataList, loStartup))
  77. {
  78. DataList->Clear();
  79. }
  80. }
  81. }
  82. //---------------------------------------------------------------------------
  83. void __fastcall Upload(TTerminal * Terminal, TStrings * FileList, bool UseDefaults)
  84. {
  85. UnicodeString TargetDirectory;
  86. TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;
  87. TargetDirectory = UnixIncludeTrailingBackslash(Terminal->CurrentDirectory);
  88. int Options = coDisableQueue;
  89. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  90. if (UseDefaults ||
  91. DoCopyDialog(true, false, FileList, TargetDirectory, &CopyParam, Options,
  92. CopyParamAttrs, NULL))
  93. {
  94. Terminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, 0);
  95. }
  96. }
  97. //---------------------------------------------------------------------------
  98. void __fastcall Download(TTerminal * Terminal, const UnicodeString FileName,
  99. bool UseDefaults)
  100. {
  101. UnicodeString TargetDirectory;
  102. TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;
  103. TStrings * FileList = NULL;
  104. try
  105. {
  106. FileList = new TStringList();
  107. TRemoteFile * File = Terminal->Files->FindFile(FileName);
  108. if (File == NULL)
  109. {
  110. throw Exception(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  111. }
  112. FileList->AddObject(FileName, File);
  113. UnicodeString LocalDirectory = ExpandFileName(Terminal->SessionData->LocalDirectory);
  114. if (LocalDirectory.IsEmpty())
  115. {
  116. LocalDirectory = GetPersonalFolder();
  117. }
  118. TargetDirectory = IncludeTrailingBackslash(LocalDirectory);
  119. int Options = coDisableQueue;
  120. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Download;
  121. if (UseDefaults ||
  122. DoCopyDialog(false, false, FileList, TargetDirectory, &CopyParam,
  123. Options, CopyParamAttrs, NULL))
  124. {
  125. Terminal->CopyToLocal(FileList, TargetDirectory, &CopyParam, 0);
  126. }
  127. }
  128. __finally
  129. {
  130. delete FileList;
  131. }
  132. }
  133. //---------------------------------------------------------------------------
  134. void __fastcall Edit(TCustomScpExplorerForm * ScpExplorer, TStrings * FileList)
  135. {
  136. ScpExplorer->StandaloneEdit(FileList->Strings[0]);
  137. Abort();
  138. }
  139. //---------------------------------------------------------------------------
  140. void __fastcall SynchronizeDirectories(TTerminal * Terminal,
  141. TStrings * CommandParams,
  142. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory)
  143. {
  144. if (CommandParams->Count >= 1)
  145. {
  146. LocalDirectory = CommandParams->Strings[0];
  147. }
  148. else if (!Terminal->SessionData->LocalDirectory.IsEmpty())
  149. {
  150. LocalDirectory = ExpandFileName(Terminal->SessionData->LocalDirectory);
  151. }
  152. else
  153. {
  154. LocalDirectory = WinConfiguration->ScpExplorer.LastLocalTargetDirectory;
  155. }
  156. if (CommandParams->Count >= 2)
  157. {
  158. RemoteDirectory = CommandParams->Strings[1];
  159. }
  160. else
  161. {
  162. RemoteDirectory = Terminal->CurrentDirectory;
  163. }
  164. }
  165. //---------------------------------------------------------------------------
  166. void __fastcall FullSynchronize(TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer,
  167. TStrings * CommandParams, bool UseDefaults)
  168. {
  169. UnicodeString LocalDirectory;
  170. UnicodeString RemoteDirectory;
  171. SynchronizeDirectories(Terminal, CommandParams, LocalDirectory, RemoteDirectory);
  172. bool SaveMode = true;
  173. // bit ugly
  174. TSynchronizeMode Mode = (TSynchronizeMode)GUIConfiguration->SynchronizeMode;
  175. if (ScpExplorer->DoFullSynchronizeDirectories(LocalDirectory,
  176. RemoteDirectory, Mode, SaveMode, UseDefaults))
  177. {
  178. if (SaveMode)
  179. {
  180. GUIConfiguration->SynchronizeMode = Mode;
  181. }
  182. Terminal->CloseOnCompletion();
  183. }
  184. else
  185. {
  186. Abort();
  187. }
  188. }
  189. //---------------------------------------------------------------------------
  190. void __fastcall Synchronize(TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer,
  191. TStrings * CommandParams, bool UseDefaults)
  192. {
  193. UnicodeString LocalDirectory;
  194. UnicodeString RemoteDirectory;
  195. SynchronizeDirectories(Terminal, CommandParams, LocalDirectory, RemoteDirectory);
  196. ScpExplorer->DoSynchronizeDirectories(LocalDirectory, RemoteDirectory, UseDefaults);
  197. Abort();
  198. }
  199. //---------------------------------------------------------------------------
  200. void __fastcall ImportSitesIfAny()
  201. {
  202. if (!WinConfiguration->AutoImportedFromPuttyOrFilezilla)
  203. {
  204. bool AnyPuttySession = GUIConfiguration->AnyPuttySessionForImport(StoredSessions);
  205. bool AnyFilezillaSession = GUIConfiguration->AnyFilezillaSessionForImport(StoredSessions);
  206. if (AnyPuttySession || AnyFilezillaSession)
  207. {
  208. UnicodeString PuttySource = LoadStrPart(IMPORT_SESSIONS2, 2);
  209. UnicodeString FilezillaSource = LoadStrPart(IMPORT_SESSIONS2, 3);
  210. UnicodeString Source;
  211. if (AnyPuttySession && AnyFilezillaSession)
  212. {
  213. Source = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 4), (PuttySource, FilezillaSource));
  214. }
  215. else if (AnyPuttySession)
  216. {
  217. Source = PuttySource;
  218. }
  219. else if (AnyFilezillaSession)
  220. {
  221. Source = FilezillaSource;
  222. }
  223. else
  224. {
  225. DebugFail();
  226. }
  227. UnicodeString Message = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 1), (Source));
  228. if (MessageDialog(Message, qtConfirmation,
  229. qaYes | qaNo, HELP_IMPORT_SESSIONS) == qaYes)
  230. {
  231. DoImportSessionsDialog(NULL);
  232. }
  233. WinConfiguration->AutoImportedFromPuttyOrFilezilla = true;
  234. }
  235. }
  236. }
  237. //---------------------------------------------------------------------------
  238. void __fastcall Usage(UnicodeString Param)
  239. {
  240. while (!Param.IsEmpty())
  241. {
  242. UnicodeString Pair = CutToChar(Param, L',', true);
  243. if (!Pair.IsEmpty())
  244. {
  245. if (Pair[Pair.Length()] == L'+')
  246. {
  247. UnicodeString Key = Pair.SubString(1, Pair.Length() - 1).Trim();
  248. Configuration->Usage->Inc(Key);
  249. }
  250. else
  251. {
  252. UnicodeString Key = CutToChar(Pair, L':', true);
  253. Configuration->Usage->Set(Key, Pair.Trim());
  254. }
  255. }
  256. }
  257. }
  258. //---------------------------------------------------------------------------
  259. void __fastcall RecordWrapperVersions(UnicodeString ConsoleVersion, UnicodeString DotNetVersion)
  260. {
  261. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  262. if (!DotNetVersion.IsEmpty())
  263. {
  264. Updates.DotNetVersion = DotNetVersion;
  265. }
  266. if (!ConsoleVersion.IsEmpty())
  267. {
  268. Updates.ConsoleVersion = ConsoleVersion;
  269. }
  270. WinConfiguration->Updates = Updates;
  271. if (Configuration->Storage == stNul)
  272. {
  273. Configuration->SetDefaultStorage();
  274. try
  275. {
  276. THierarchicalStorage * Storage = Configuration->CreateConfigStorage();
  277. try
  278. {
  279. Storage->AccessMode = smReadWrite;
  280. if (Storage->OpenSubKey(Configuration->ConfigurationSubKey, true) &&
  281. Storage->OpenSubKey(L"Interface\\Updates", true, true))
  282. {
  283. if (!DotNetVersion.IsEmpty())
  284. {
  285. Storage->WriteString(L"DotNetVersion", DotNetVersion);
  286. }
  287. if (!ConsoleVersion.IsEmpty())
  288. {
  289. Storage->WriteString(L"ConsoleVersion", ConsoleVersion);
  290. }
  291. }
  292. }
  293. __finally
  294. {
  295. delete Storage;
  296. }
  297. }
  298. __finally
  299. {
  300. Configuration->SetNulStorage();
  301. }
  302. }
  303. }
  304. //---------------------------------------------------------------------------
  305. static UnicodeString ColorToRGBStr(TColor Color)
  306. {
  307. int RGB = ColorToRGB(Color);
  308. int R = GetRValue(RGB);
  309. int G = GetGValue(RGB);
  310. int B = GetBValue(RGB);
  311. UnicodeString Result = FORMAT(L"%.2x%.2x%.2x", (R, G, B));
  312. return Result;
  313. }
  314. //---------------------------------------------------------------------------
  315. void __fastcall UpdateStaticUsage()
  316. {
  317. Configuration->Usage->Inc(L"Runs");
  318. Configuration->Usage->UpdateCurrentVersion();
  319. UnicodeString WindowsVersion = FORMAT("%d.%d.%d %s", (Win32MajorVersion, Win32MinorVersion, Win32BuildNumber, Win32CSDVersion));
  320. Configuration->Usage->Set(L"WindowsVersion", (WindowsVersion));
  321. Configuration->Usage->Set(L"WindowsProductName", (WindowsProductName()));
  322. DWORD Type;
  323. GetWindowsProductType(Type);
  324. Configuration->Usage->Set(L"WindowsProductType", (static_cast<int>(Type)));
  325. Configuration->Usage->Set(L"Windows64", IsWin64());
  326. Configuration->Usage->Set(L"DefaultLocale",
  327. IntToHex(static_cast<int>(GetDefaultLCID()), 4));
  328. Configuration->Usage->Set(L"Locale",
  329. IntToHex(static_cast<int>(WinConfiguration->Locale), 4));
  330. Configuration->Usage->Set(L"PixelsPerInch", Screen->PixelsPerInch);
  331. bool PixelsPerInchSystemDiffers = false;
  332. bool PixelsPerInchMonitorsDiffer = false;
  333. bool PixelsPerInchAxesDiffer = false;
  334. HINSTANCE ShCoreLibrary = LoadLibrary(L"shcore.dll");
  335. if (ShCoreLibrary != NULL)
  336. {
  337. GetDpiForMonitorProc GetDpiForMonitor =
  338. (GetDpiForMonitorProc)GetProcAddress(ShCoreLibrary, "GetDpiForMonitor");
  339. if (GetDpiForMonitor != NULL)
  340. {
  341. unsigned int PrimaryDpiX;
  342. unsigned int PrimaryDpiY;
  343. for (int Index = 0; Index < Screen->MonitorCount; Index++)
  344. {
  345. unsigned int DpiX;
  346. unsigned int DpiY;
  347. GetDpiForMonitor(Screen->Monitors[Index]->Handle, MDT_Default, &DpiX, &DpiY);
  348. if (DpiX != DpiY)
  349. {
  350. PixelsPerInchAxesDiffer = true;
  351. }
  352. if (Index == 0)
  353. {
  354. PrimaryDpiX = DpiX;
  355. PrimaryDpiY = DpiY;
  356. // PixelsPerInch is GetDeviceCaps(DC, LOGPIXELSY)
  357. if (DpiY != (unsigned int)Screen->PixelsPerInch)
  358. {
  359. PixelsPerInchSystemDiffers = true;
  360. }
  361. }
  362. else
  363. {
  364. if ((DpiX != PrimaryDpiX) ||
  365. (DpiY != PrimaryDpiY))
  366. {
  367. PixelsPerInchMonitorsDiffer = true;
  368. }
  369. }
  370. }
  371. }
  372. }
  373. if (PixelsPerInchSystemDiffers)
  374. {
  375. Configuration->Usage->Inc(L"PixelsPerInchSystemDiffered");
  376. }
  377. Configuration->Usage->Set(L"PixelsPerInchMonitorsDiffer", PixelsPerInchMonitorsDiffer);
  378. Configuration->Usage->Set(L"PixelsPerInchAxesDiffer", PixelsPerInchAxesDiffer);
  379. Configuration->Usage->Set(L"WorkAreaWidth", Screen->WorkAreaWidth);
  380. Configuration->Usage->Set(L"WorkAreaHeight", Screen->WorkAreaHeight);
  381. HDC DC = GetDC(NULL);
  382. int Planes = GetDeviceCaps(DC, PLANES);
  383. int BitsPixel = GetDeviceCaps(DC, BITSPIXEL);
  384. Configuration->Usage->Set(L"ColorDepth", Planes * BitsPixel);
  385. Configuration->Usage->Set(L"MonitorCount", Screen->MonitorCount);
  386. Configuration->Usage->Set(L"NotUseThemes", !UseThemes());
  387. Configuration->Usage->Set(L"ThemeDefaultFontSize", Application->DefaultFont->Size);
  388. Configuration->Usage->Set(L"ThemeIconFontSize", Screen->IconFont->Size);
  389. Configuration->Usage->Set(L"SysColorWindow", ColorToRGBStr(clWindow));
  390. Configuration->Usage->Set(L"SysColorBtnFace", ColorToRGBStr(clBtnFace));
  391. Configuration->Usage->Set(L"SysColorWindowText", ColorToRGBStr(clWindowText));
  392. UnicodeString ProgramsFolder;
  393. ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);
  394. ProgramsFolder = IncludeTrailingBackslash(ExpandFileName(ProgramsFolder));
  395. UnicodeString ExeName = ExpandFileName(Application->ExeName);
  396. bool InProgramFiles = AnsiSameText(ExeName.SubString(1, ProgramsFolder.Length()), ProgramsFolder);
  397. Configuration->Usage->Set(L"InProgramFiles", InProgramFiles);
  398. Configuration->Usage->Set(L"IsInstalled", IsInstalled());
  399. Configuration->Usage->Set(L"Wine", IsWine());
  400. WinConfiguration->UpdateStaticUsage();
  401. }
  402. //---------------------------------------------------------------------------
  403. void __fastcall MaintenanceTask()
  404. {
  405. CoreMaintenanceTask();
  406. }
  407. //---------------------------------------------------------------------------
  408. struct TFindProcessMainWindowParam
  409. {
  410. unsigned long ProcessId;
  411. HWND HiddenWindow;
  412. HWND MainWindow;
  413. };
  414. //---------------------------------------------------------------------------
  415. BOOL __stdcall FindProcessMainWindow(HWND Handle, LPARAM AParam)
  416. {
  417. TFindProcessMainWindowParam & Param = *reinterpret_cast<TFindProcessMainWindowParam *>(AParam);
  418. unsigned long ProcessId;
  419. if ((Handle != Param.HiddenWindow) &&
  420. (Param.MainWindow == 0) && // optimization
  421. (GetWindowThreadProcessId(Handle, &ProcessId) != 0) &&
  422. (ProcessId == Param.ProcessId))
  423. {
  424. TCopyDataMessage Message;
  425. Message.Version = TCopyDataMessage::Version1;
  426. COPYDATASTRUCT CopyData;
  427. CopyData.cbData = sizeof(Message);
  428. CopyData.lpData = &Message;
  429. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  430. LRESULT SendResult =
  431. SendMessage(Handle, WM_COPYDATA, reinterpret_cast<WPARAM>(HInstance),
  432. reinterpret_cast<LPARAM>(&CopyData));
  433. if (SendResult > 0)
  434. {
  435. Param.MainWindow = Handle;
  436. }
  437. }
  438. return TRUE;
  439. }
  440. //---------------------------------------------------------------------------
  441. bool __fastcall SendToAnotherInstance()
  442. {
  443. HWND HiddenWindow = FindWindow(HIDDEN_WINDOW_NAME, NULL);
  444. bool Result = (HiddenWindow != NULL);
  445. if (Result)
  446. {
  447. TCopyDataMessage Message;
  448. Message.Version = TCopyDataMessage::Version1;
  449. COPYDATASTRUCT CopyData;
  450. CopyData.cbData = sizeof(Message);
  451. CopyData.lpData = &Message;
  452. // this test is actually redundant, it just a kind of optimization to avoid expensive
  453. // EnumWindows, we can achieve the same by testing FindProcessMainWindowParam.MainWindow,
  454. // before sending CommandCommandLine
  455. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  456. LRESULT SendResult =
  457. SendMessage(HiddenWindow, WM_COPYDATA, reinterpret_cast<WPARAM>(HInstance),
  458. reinterpret_cast<LPARAM>(&CopyData));
  459. Result = (SendResult > 0);
  460. if (Result)
  461. {
  462. TFindProcessMainWindowParam FindProcessMainWindowParam;
  463. if (GetWindowThreadProcessId(HiddenWindow, &FindProcessMainWindowParam.ProcessId) != 0)
  464. {
  465. FindProcessMainWindowParam.HiddenWindow = HiddenWindow;
  466. FindProcessMainWindowParam.MainWindow = 0;
  467. if (EnumWindows(FindProcessMainWindow, reinterpret_cast<LPARAM>(&FindProcessMainWindowParam)) &&
  468. (FindProcessMainWindowParam.MainWindow != 0))
  469. {
  470. // Restore window, if minimized
  471. ShowWindow(FindProcessMainWindowParam.MainWindow, SW_RESTORE);
  472. // bring it to foreground
  473. SetForegroundWindow(FindProcessMainWindowParam.MainWindow);
  474. }
  475. }
  476. Message.Command = TCopyDataMessage::CommandCommandLine;
  477. wcsncpy(Message.CommandLine, CmdLine, LENOF(Message.CommandLine));
  478. NULL_TERMINATE(Message.CommandLine);
  479. LRESULT SendResult =
  480. SendMessage(HiddenWindow, WM_COPYDATA,
  481. reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));
  482. Result = (SendResult > 0);
  483. }
  484. }
  485. return Result;
  486. }
  487. //---------------------------------------------------------------------------
  488. bool __fastcall ShowUpdatesIfAvailable()
  489. {
  490. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  491. int CurrentCompoundVer = Configuration->CompoundVersion;
  492. bool NoPopup = true;
  493. bool Result =
  494. Updates.ShowOnStartup &&
  495. Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&
  496. !Updates.Results.Disabled &&
  497. ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&
  498. !Updates.ShownResults;
  499. if (Result)
  500. {
  501. Configuration->Usage->Inc(L"UpdateStartup");
  502. Result = CheckForUpdates(true);
  503. if (Result)
  504. {
  505. Configuration->Usage->Inc(L"UpdateDownloadOpensStartup");
  506. }
  507. NoPopup = false;
  508. }
  509. else if (WinConfiguration->ShowTips)
  510. {
  511. int Days = DaysBetween(WinConfiguration->TipsShown, Now());
  512. if ((Days >= Updates.Results.TipsIntervalDays) &&
  513. (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))
  514. {
  515. UnicodeString Tip = FirstUnshownTip();
  516. if (!Tip.IsEmpty())
  517. {
  518. AutoShowNewTip();
  519. NoPopup = false;
  520. }
  521. else
  522. {
  523. Configuration->Usage->Inc(L"TipsNoUnseen");
  524. }
  525. }
  526. }
  527. if (NoPopup)
  528. {
  529. WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;
  530. }
  531. return Result;
  532. }
  533. //---------------------------------------------------------------------------
  534. int __fastcall Execute()
  535. {
  536. DebugAssert(StoredSessions);
  537. TProgramParams * Params = TProgramParams::Instance();
  538. DebugAssert(Params);
  539. // do not flash message boxes on startup
  540. SetOnForeground(true);
  541. // let installer know, that some instance of application is running
  542. CreateMutex(NULL, False, AppName.c_str());
  543. bool OnlyInstance = (GetLastError() == 0);
  544. UpdateStaticUsage();
  545. UnicodeString KeyFile;
  546. if (Params->FindSwitch(L"PrivateKey", KeyFile))
  547. {
  548. WinConfiguration->DefaultKeyFile = KeyFile;
  549. }
  550. UnicodeString ConsoleVersion;
  551. UnicodeString DotNetVersion;
  552. Params->FindSwitch(L"Console", ConsoleVersion);
  553. Params->FindSwitch(L"DotNet", DotNetVersion);
  554. if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())
  555. {
  556. RecordWrapperVersions(ConsoleVersion, DotNetVersion);
  557. }
  558. if (!DotNetVersion.IsEmpty())
  559. {
  560. Configuration->Usage->Inc(L"ConsoleDotNet");
  561. }
  562. UnicodeString SwitchValue;
  563. if (Params->FindSwitch(L"loglevel", SwitchValue))
  564. {
  565. int StarPos = SwitchValue.Pos(L"*");
  566. if (StarPos > 0)
  567. {
  568. bool LogSensitive = true;
  569. SwitchValue.Delete(StarPos, 1);
  570. if ((StarPos <= SwitchValue.Length()) &&
  571. (SwitchValue[StarPos] == L'-'))
  572. {
  573. LogSensitive = false;
  574. SwitchValue.Delete(StarPos, 1);
  575. }
  576. SwitchValue = SwitchValue.Trim();
  577. Configuration->TemporaryLogSensitive(LogSensitive);
  578. }
  579. int LogProtocol;
  580. if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= 0))
  581. {
  582. Configuration->TemporaryLogProtocol(LogProtocol);
  583. }
  584. }
  585. TConsoleMode Mode = cmNone;
  586. if (Params->FindSwitch(L"help") || Params->FindSwitch(L"h") || Params->FindSwitch(L"?"))
  587. {
  588. Mode = cmHelp;
  589. }
  590. else if (Params->FindSwitch(L"batchsettings"))
  591. {
  592. Mode = cmBatchSettings;
  593. }
  594. else if (Params->FindSwitch(KEYGEN_SWITCH))
  595. {
  596. Mode = cmKeyGen;
  597. }
  598. // We have to check for /console only after the other options,
  599. // as the /console is always used when we are run by winscp.com
  600. // (ambiguous use to pass console version)
  601. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(L"script") ||
  602. Params->FindSwitch(COMMAND_SWITCH))
  603. {
  604. Mode = cmScripting;
  605. }
  606. if (Mode != cmNone)
  607. {
  608. return Console(Mode);
  609. }
  610. TTerminalManager * TerminalManager = NULL;
  611. GlyphsModule = NULL;
  612. NonVisualDataModule = NULL;
  613. TStrings * CommandParams = new TStringList;
  614. try
  615. {
  616. TerminalManager = TTerminalManager::Instance();
  617. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  618. try
  619. {
  620. GlyphsModule = new TGlyphsModule(Application);
  621. }
  622. __finally
  623. {
  624. GUIConfiguration->ChangeResourceModule(ResourceModule);
  625. }
  626. NonVisualDataModule = new TNonVisualDataModule(Application);
  627. LogForm = NULL;
  628. Application->HintHidePause = 3000;
  629. UnicodeString IniFileName = Params->SwitchValue(L"ini");
  630. if (!IniFileName.IsEmpty())
  631. {
  632. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  633. if (!FileExists(ApiPath(IniFileNameExpanded)))
  634. {
  635. // this should be displayed rather at the very beginning.
  636. // however for simplicity (GUI-only), we do it only here.
  637. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  638. }
  639. }
  640. if (Params->FindSwitch(L"UninstallCleanup"))
  641. {
  642. MaintenanceTask();
  643. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  644. // workaround is that we create mutex in uninstaller, if it runs silent, and
  645. // ignore the UninstallCleanup, when the mutex exists.
  646. if ((OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL) &&
  647. (MessageDialog(MainInstructions(LoadStr(UNINSTALL_CLEANUP)), qtConfirmation,
  648. qaYes | qaNo, HELP_UNINSTALL_CLEANUP) == qaYes))
  649. {
  650. DoCleanupDialog(StoredSessions, Configuration);
  651. }
  652. }
  653. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  654. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  655. {
  656. MaintenanceTask();
  657. if (CheckSafe(Params))
  658. {
  659. RegisterForDefaultProtocols();
  660. Configuration->DontSave();
  661. }
  662. }
  663. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  664. {
  665. MaintenanceTask();
  666. if (CheckSafe(Params))
  667. {
  668. UnregisterForProtocols();
  669. Configuration->DontSave();
  670. }
  671. }
  672. else if (Params->FindSwitch(L"AddSearchPath"))
  673. {
  674. MaintenanceTask();
  675. if (CheckSafe(Params))
  676. {
  677. AddSearchPath(ExtractFilePath(Application->ExeName));
  678. Configuration->DontSave();
  679. }
  680. }
  681. else if (Params->FindSwitch(L"RemoveSearchPath"))
  682. {
  683. MaintenanceTask();
  684. if (CheckSafe(Params))
  685. {
  686. try
  687. {
  688. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  689. }
  690. catch(...)
  691. {
  692. // ignore errors
  693. // (RemoveSearchPath is called always on uninstallation,
  694. // even if AddSearchPath was not used, so we would get the error
  695. // always for non-priviledged user)
  696. }
  697. Configuration->DontSave();
  698. }
  699. }
  700. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  701. {
  702. MaintenanceTask();
  703. ImportSitesIfAny();
  704. }
  705. else if (Params->FindSwitch(L"Usage", SwitchValue))
  706. {
  707. MaintenanceTask();
  708. Usage(SwitchValue);
  709. }
  710. else if (Params->FindSwitch(L"Update"))
  711. {
  712. MaintenanceTask();
  713. CheckForUpdates(false);
  714. }
  715. else if (ShowUpdatesIfAvailable())
  716. {
  717. // noop
  718. }
  719. else if (Params->FindSwitch(L"Exit"))
  720. {
  721. // noop
  722. MaintenanceTask();
  723. Configuration->DontSave();
  724. }
  725. else if (Params->FindSwitch(L"MaintenanceTask"))
  726. {
  727. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  728. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  729. MaintenanceTask();
  730. Configuration->DontSave();
  731. }
  732. else
  733. {
  734. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit } ParamCommand;
  735. ParamCommand = pcNone;
  736. UnicodeString AutoStartSession;
  737. UnicodeString DownloadFile;
  738. bool UseDefaults = false;
  739. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  740. if (OnlyInstance &&
  741. WinConfiguration->TemporaryDirectoryCleanup)
  742. {
  743. TemporaryDirectoryCleanup();
  744. }
  745. WinConfiguration->CheckDefaultTranslation();
  746. if (!Params->Empty)
  747. {
  748. if (Params->FindSwitch(L"Defaults") && CheckSafe(Params))
  749. {
  750. UseDefaults = true;
  751. }
  752. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  753. {
  754. ParamCommand = pcUpload;
  755. if (CommandParams->Count == 0)
  756. {
  757. throw Exception(NO_UPLOAD_LIST_ERROR);
  758. }
  759. }
  760. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  761. {
  762. if (CommandParams->Count > 0)
  763. {
  764. ParamCommand = pcUpload;
  765. }
  766. }
  767. else if (Params->FindSwitch(L"Synchronize", CommandParams, 2))
  768. {
  769. ParamCommand = pcFullSynchronize;
  770. }
  771. else if (Params->FindSwitch(L"KeepUpToDate", CommandParams, 2))
  772. {
  773. ParamCommand = pcSynchronize;
  774. }
  775. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  776. (CommandParams->Count == 1))
  777. {
  778. ParamCommand = pcEdit;
  779. }
  780. }
  781. if (Params->ParamCount > 0)
  782. {
  783. if ((ParamCommand == pcNone) &&
  784. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  785. !Params->FindSwitch(NEWINSTANCE_SWICH) &&
  786. SendToAnotherInstance())
  787. {
  788. Configuration->Usage->Inc(L"SendToAnotherInstance");
  789. return 0;
  790. }
  791. AutoStartSession = Params->Param[1];
  792. Params->ParamsProcessed(1, 1);
  793. UnicodeString CounterName;
  794. if (Params->FindSwitch(JUMPLIST_SWITCH))
  795. {
  796. CounterName = L"CommandLineJumpList";
  797. }
  798. else if (Params->FindSwitch(DESKTOP_SWITCH))
  799. {
  800. CounterName = L"CommandLineDesktop";
  801. }
  802. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  803. {
  804. CounterName = L"CommandLineSendToHook";
  805. }
  806. else
  807. {
  808. CounterName = L"CommandLineSession2";
  809. }
  810. Configuration->Usage->Inc(CounterName);
  811. }
  812. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  813. {
  814. AutoStartSession = StoredSessions->Sessions[0]->Name;
  815. }
  816. else
  817. {
  818. AutoStartSession = WinConfiguration->AutoStartSession;
  819. }
  820. // from now flash message boxes on background
  821. SetOnForeground(false);
  822. bool CommandLineOperation = (ParamCommand != pcNone) || !DownloadFile.IsEmpty();
  823. bool NeedSession = CommandLineOperation;
  824. bool Retry;
  825. do
  826. {
  827. Retry = false;
  828. TObjectList * DataList = new TObjectList();
  829. GetLoginData(AutoStartSession, Params, DataList, DownloadFile, NeedSession);
  830. try
  831. {
  832. if (!NeedSession || (DataList->Count > 0))
  833. {
  834. if (CheckSafe(Params))
  835. {
  836. UnicodeString LogFile;
  837. if (Params->FindSwitch(L"Log", LogFile))
  838. {
  839. Configuration->TemporaryLogging(LogFile);
  840. }
  841. if (Params->FindSwitch(L"XmlLog", LogFile))
  842. {
  843. Configuration->TemporaryActionsLogging(LogFile);
  844. }
  845. }
  846. try
  847. {
  848. DebugAssert(!TerminalManager->ActiveTerminal);
  849. bool CanStart;
  850. if (DataList->Count > 0)
  851. {
  852. TerminalManager->ActiveTerminal =
  853. TerminalManager->NewTerminals(DataList);
  854. CanStart = (TerminalManager->Count > 0);
  855. }
  856. else
  857. {
  858. DebugAssert(!NeedSession);
  859. CanStart = true;
  860. }
  861. if (!CanStart)
  862. {
  863. // do not prompt with login dialog, if connection of
  864. // auto-start session (typically from command line) failed
  865. if (AutoStartSession.IsEmpty())
  866. {
  867. Retry = true;
  868. }
  869. }
  870. else
  871. {
  872. // from now on, we do not support runtime interface change
  873. CustomWinConfiguration->CanApplyInterfaceImmediately = false;
  874. TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();
  875. CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;
  876. try
  877. {
  878. // moved inside try .. __finally, because it can fail as well
  879. TerminalManager->ScpExplorer = ScpExplorer;
  880. if (CommandLineOperation)
  881. {
  882. Configuration->Usage->Inc(L"CommandLineOperation");
  883. }
  884. if (ParamCommand == pcUpload)
  885. {
  886. Upload(TerminalManager->ActiveTerminal, CommandParams, UseDefaults);
  887. }
  888. else if (ParamCommand == pcFullSynchronize)
  889. {
  890. FullSynchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  891. CommandParams, UseDefaults);
  892. }
  893. else if (ParamCommand == pcSynchronize)
  894. {
  895. Synchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  896. CommandParams, UseDefaults);
  897. }
  898. else if (ParamCommand == pcEdit)
  899. {
  900. Edit(ScpExplorer, CommandParams);
  901. }
  902. else if (!DownloadFile.IsEmpty())
  903. {
  904. Download(TerminalManager->ActiveTerminal, DownloadFile,
  905. UseDefaults);
  906. }
  907. Application->Run();
  908. }
  909. __finally
  910. {
  911. TerminalManager->ScpExplorer = NULL;
  912. SAFE_DESTROY(ScpExplorer);
  913. }
  914. }
  915. }
  916. catch (Exception &E)
  917. {
  918. ShowExtendedException(&E);
  919. }
  920. }
  921. }
  922. __finally
  923. {
  924. delete DataList;
  925. }
  926. }
  927. while (Retry);
  928. }
  929. }
  930. __finally
  931. {
  932. delete NonVisualDataModule;
  933. NonVisualDataModule = NULL;
  934. delete GlyphsModule;
  935. GlyphsModule = NULL;
  936. TTerminalManager::DestroyInstance();
  937. delete CommandParams;
  938. }
  939. return 0;
  940. }