WinMain.cpp 33 KB

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