WinMain.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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))
  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))
  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(L"script") ||
  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. Application->HintHidePause = 3000;
  638. UnicodeString IniFileName = Params->SwitchValue(INI_SWITCH);
  639. if (!IniFileName.IsEmpty())
  640. {
  641. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  642. if (!FileExists(ApiPath(IniFileNameExpanded)))
  643. {
  644. // this should be displayed rather at the very beginning.
  645. // however for simplicity (GUI-only), we do it only here.
  646. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  647. }
  648. }
  649. if (Params->FindSwitch(L"UninstallCleanup"))
  650. {
  651. MaintenanceTask();
  652. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  653. // workaround is that we create mutex in uninstaller, if it runs silent, and
  654. // ignore the UninstallCleanup, when the mutex exists.
  655. if ((OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL) &&
  656. (MessageDialog(MainInstructions(LoadStr(UNINSTALL_CLEANUP)), qtConfirmation,
  657. qaYes | qaNo, HELP_UNINSTALL_CLEANUP) == qaYes))
  658. {
  659. DoCleanupDialog(StoredSessions, Configuration);
  660. }
  661. }
  662. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  663. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  664. {
  665. MaintenanceTask();
  666. if (CheckSafe(Params))
  667. {
  668. RegisterForDefaultProtocols();
  669. Configuration->DontSave();
  670. }
  671. }
  672. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  673. {
  674. MaintenanceTask();
  675. if (CheckSafe(Params))
  676. {
  677. UnregisterForProtocols();
  678. Configuration->DontSave();
  679. }
  680. }
  681. else if (Params->FindSwitch(L"AddSearchPath"))
  682. {
  683. MaintenanceTask();
  684. if (CheckSafe(Params))
  685. {
  686. AddSearchPath(ExtractFilePath(Application->ExeName));
  687. Configuration->DontSave();
  688. }
  689. }
  690. else if (Params->FindSwitch(L"RemoveSearchPath"))
  691. {
  692. MaintenanceTask();
  693. if (CheckSafe(Params))
  694. {
  695. try
  696. {
  697. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  698. }
  699. catch(...)
  700. {
  701. // ignore errors
  702. // (RemoveSearchPath is called always on uninstallation,
  703. // even if AddSearchPath was not used, so we would get the error
  704. // always for non-priviledged user)
  705. }
  706. Configuration->DontSave();
  707. }
  708. }
  709. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  710. {
  711. MaintenanceTask();
  712. ImportSitesIfAny();
  713. }
  714. else if (Params->FindSwitch(L"Usage", SwitchValue))
  715. {
  716. MaintenanceTask();
  717. Usage(SwitchValue);
  718. }
  719. else if (Params->FindSwitch(L"Update"))
  720. {
  721. MaintenanceTask();
  722. CheckForUpdates(false);
  723. }
  724. else if (ShowUpdatesIfAvailable())
  725. {
  726. // noop
  727. }
  728. else if (Params->FindSwitch(L"Exit"))
  729. {
  730. // noop
  731. MaintenanceTask();
  732. Configuration->DontSave();
  733. }
  734. else if (Params->FindSwitch(L"MaintenanceTask"))
  735. {
  736. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  737. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  738. MaintenanceTask();
  739. Configuration->DontSave();
  740. }
  741. else
  742. {
  743. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit } ParamCommand;
  744. ParamCommand = pcNone;
  745. UnicodeString AutoStartSession;
  746. UnicodeString DownloadFile;
  747. bool UseDefaults = false;
  748. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  749. if (OnlyInstance &&
  750. WinConfiguration->TemporaryDirectoryCleanup)
  751. {
  752. TemporaryDirectoryCleanup();
  753. }
  754. WinConfiguration->CheckDefaultTranslation();
  755. if (!Params->Empty)
  756. {
  757. if (Params->FindSwitch(L"Defaults") && CheckSafe(Params))
  758. {
  759. UseDefaults = true;
  760. }
  761. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  762. {
  763. ParamCommand = pcUpload;
  764. if (CommandParams->Count == 0)
  765. {
  766. throw Exception(NO_UPLOAD_LIST_ERROR);
  767. }
  768. }
  769. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  770. {
  771. if (CommandParams->Count > 0)
  772. {
  773. ParamCommand = pcUpload;
  774. }
  775. }
  776. else if (Params->FindSwitch(L"Synchronize", CommandParams, 2))
  777. {
  778. ParamCommand = pcFullSynchronize;
  779. }
  780. else if (Params->FindSwitch(L"KeepUpToDate", CommandParams, 2))
  781. {
  782. ParamCommand = pcSynchronize;
  783. }
  784. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  785. (CommandParams->Count == 1))
  786. {
  787. ParamCommand = pcEdit;
  788. }
  789. }
  790. if (Params->ParamCount > 0)
  791. {
  792. if ((ParamCommand == pcNone) &&
  793. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  794. !Params->FindSwitch(NEWINSTANCE_SWICH) &&
  795. SendToAnotherInstance())
  796. {
  797. Configuration->Usage->Inc(L"SendToAnotherInstance");
  798. return 0;
  799. }
  800. AutoStartSession = Params->Param[1];
  801. Params->ParamsProcessed(1, 1);
  802. UnicodeString CounterName;
  803. if (Params->FindSwitch(JUMPLIST_SWITCH))
  804. {
  805. CounterName = L"CommandLineJumpList";
  806. }
  807. else if (Params->FindSwitch(DESKTOP_SWITCH))
  808. {
  809. CounterName = L"CommandLineDesktop";
  810. }
  811. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  812. {
  813. CounterName = L"CommandLineSendToHook";
  814. }
  815. else
  816. {
  817. CounterName = L"CommandLineSession2";
  818. }
  819. Configuration->Usage->Inc(CounterName);
  820. }
  821. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  822. {
  823. AutoStartSession = StoredSessions->Sessions[0]->Name;
  824. }
  825. else
  826. {
  827. AutoStartSession = WinConfiguration->AutoStartSession;
  828. }
  829. // from now flash message boxes on background
  830. SetOnForeground(false);
  831. bool CommandLineOperation = (ParamCommand != pcNone) || !DownloadFile.IsEmpty();
  832. bool NeedSession = CommandLineOperation;
  833. bool Retry;
  834. do
  835. {
  836. Retry = false;
  837. TObjectList * DataList = new TObjectList();
  838. try
  839. {
  840. GetLoginData(AutoStartSession, Params, DataList, DownloadFile, NeedSession);
  841. // GetLoginData now Aborts when session is needed and none is selected
  842. if (DebugAlwaysTrue(!NeedSession || (DataList->Count > 0)))
  843. {
  844. if (CheckSafe(Params))
  845. {
  846. UnicodeString LogFile;
  847. if (Params->FindSwitch(LOG_SWITCH, LogFile))
  848. {
  849. Configuration->TemporaryLogging(LogFile);
  850. }
  851. if (Params->FindSwitch(L"XmlLog", LogFile))
  852. {
  853. Configuration->TemporaryActionsLogging(LogFile);
  854. }
  855. }
  856. try
  857. {
  858. DebugAssert(!TerminalManager->ActiveTerminal);
  859. bool CanStart;
  860. if (DataList->Count > 0)
  861. {
  862. TerminalManager->ActiveTerminal =
  863. TerminalManager->NewTerminals(DataList);
  864. CanStart = (TerminalManager->Count > 0);
  865. }
  866. else
  867. {
  868. DebugAssert(!NeedSession);
  869. CanStart = true;
  870. }
  871. if (!CanStart)
  872. {
  873. // do not prompt with login dialog, if connection of
  874. // auto-start session (typically from command line) failed
  875. if (AutoStartSession.IsEmpty())
  876. {
  877. Retry = true;
  878. }
  879. }
  880. else
  881. {
  882. // from now on, we do not support runtime interface change
  883. CustomWinConfiguration->CanApplyInterfaceImmediately = false;
  884. TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();
  885. CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;
  886. try
  887. {
  888. // moved inside try .. __finally, because it can fail as well
  889. TerminalManager->ScpExplorer = ScpExplorer;
  890. if (CommandLineOperation)
  891. {
  892. Configuration->Usage->Inc(L"CommandLineOperation");
  893. }
  894. if (ParamCommand == pcUpload)
  895. {
  896. Upload(TerminalManager->ActiveTerminal, CommandParams, UseDefaults);
  897. }
  898. else if (ParamCommand == pcFullSynchronize)
  899. {
  900. FullSynchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  901. CommandParams, UseDefaults);
  902. }
  903. else if (ParamCommand == pcSynchronize)
  904. {
  905. Synchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  906. CommandParams, UseDefaults);
  907. }
  908. else if (ParamCommand == pcEdit)
  909. {
  910. Edit(ScpExplorer, CommandParams);
  911. }
  912. else if (!DownloadFile.IsEmpty())
  913. {
  914. Download(TerminalManager->ActiveTerminal, DownloadFile,
  915. UseDefaults);
  916. }
  917. Application->Run();
  918. }
  919. __finally
  920. {
  921. TerminalManager->ScpExplorer = NULL;
  922. SAFE_DESTROY(ScpExplorer);
  923. }
  924. }
  925. }
  926. catch (Exception &E)
  927. {
  928. ShowExtendedException(&E);
  929. }
  930. }
  931. }
  932. __finally
  933. {
  934. delete DataList;
  935. }
  936. }
  937. while (Retry);
  938. }
  939. }
  940. __finally
  941. {
  942. delete NonVisualDataModule;
  943. NonVisualDataModule = NULL;
  944. ReleaseAnimationsModule();
  945. delete GlyphsModule;
  946. GlyphsModule = NULL;
  947. TTerminalManager::DestroyInstance();
  948. delete CommandParams;
  949. }
  950. return 0;
  951. }