WinMain.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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. bool Close = false;
  28. if (StoredSessions->IsFolder(SessionName) ||
  29. StoredSessions->IsWorkspace(SessionName))
  30. {
  31. StoredSessions->GetFolderOrWorkspace(SessionName, DataList);
  32. }
  33. else
  34. {
  35. TSessionData * SessionData =
  36. StoredSessions->ParseUrl(SessionName, Options, DefaultsOnly,
  37. &DownloadFile);
  38. DataList->Add(SessionData);
  39. if (DataList->Count == 1)
  40. {
  41. TSessionData * SessionData = DebugNotNull(dynamic_cast<TSessionData *>(DataList->Items[0]));
  42. if (SessionData->SaveOnly)
  43. {
  44. Configuration->Usage->Inc(L"CommandLineSessionSave");
  45. TSessionData * SavedSession = DoSaveSession(SessionData, NULL, true, NULL);
  46. Close = (SavedSession == NULL);
  47. if (!Close)
  48. {
  49. WinConfiguration->LastStoredSession = SavedSession->Name;
  50. }
  51. DataList->Clear();
  52. }
  53. else if (!SessionData->PuttyProtocol.IsEmpty())
  54. {
  55. // putty does not support resolving environment variables in session settings
  56. // though it's hardly of any use here.
  57. SessionData->ExpandEnvironmentVariables();
  58. OpenSessionInPutty(GUIConfiguration->PuttyPath, SessionData);
  59. DataList->Clear();
  60. Close = true;
  61. }
  62. }
  63. }
  64. if (!Close)
  65. {
  66. if (DefaultsOnly && !NeedSession)
  67. {
  68. // No URL specified on command-line and no explicit command-line parameter
  69. // that results session was specified => noop
  70. DataList->Clear();
  71. }
  72. else if ((DataList->Count == 0) ||
  73. !dynamic_cast<TSessionData *>(DataList->Items[0])->CanLogin ||
  74. DefaultsOnly)
  75. {
  76. // Note that GetFolderOrWorkspace never returns sites that !CanLogin,
  77. // so we should not get here with more then one site.
  78. // Though we should be good, if we ever do.
  79. DebugAssert(DataList->Count <= 1);
  80. if (!DoLoginDialog(StoredSessions, DataList, loStartup))
  81. {
  82. DataList->Clear();
  83. }
  84. }
  85. }
  86. }
  87. //---------------------------------------------------------------------------
  88. void __fastcall Upload(TTerminal * Terminal, TStrings * FileList, bool UseDefaults)
  89. {
  90. UnicodeString TargetDirectory;
  91. TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;
  92. TargetDirectory = UnixIncludeTrailingBackslash(Terminal->CurrentDirectory);
  93. int Options = coDisableQueue;
  94. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  95. if (UseDefaults ||
  96. DoCopyDialog(true, false, FileList, TargetDirectory, &CopyParam, Options,
  97. CopyParamAttrs, NULL))
  98. {
  99. Terminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, 0);
  100. }
  101. }
  102. //---------------------------------------------------------------------------
  103. void __fastcall Download(TTerminal * Terminal, const UnicodeString FileName,
  104. bool UseDefaults)
  105. {
  106. UnicodeString TargetDirectory;
  107. TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;
  108. TStrings * FileList = NULL;
  109. try
  110. {
  111. FileList = new TStringList();
  112. TRemoteFile * File = Terminal->Files->FindFile(FileName);
  113. if (File == NULL)
  114. {
  115. throw Exception(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  116. }
  117. FileList->AddObject(FileName, File);
  118. UnicodeString LocalDirectory = ExpandFileName(Terminal->SessionData->LocalDirectory);
  119. if (LocalDirectory.IsEmpty())
  120. {
  121. LocalDirectory = GetPersonalFolder();
  122. }
  123. TargetDirectory = IncludeTrailingBackslash(LocalDirectory);
  124. int Options = coDisableQueue;
  125. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Download;
  126. if (UseDefaults ||
  127. DoCopyDialog(false, false, FileList, TargetDirectory, &CopyParam,
  128. Options, CopyParamAttrs, NULL))
  129. {
  130. Terminal->CopyToLocal(FileList, TargetDirectory, &CopyParam, 0);
  131. }
  132. }
  133. __finally
  134. {
  135. delete FileList;
  136. }
  137. }
  138. //---------------------------------------------------------------------------
  139. void __fastcall Edit(TCustomScpExplorerForm * ScpExplorer, TStrings * FileList)
  140. {
  141. ScpExplorer->StandaloneEdit(FileList->Strings[0]);
  142. Abort();
  143. }
  144. //---------------------------------------------------------------------------
  145. void __fastcall SynchronizeDirectories(TTerminal * Terminal,
  146. TStrings * CommandParams,
  147. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory)
  148. {
  149. if (CommandParams->Count >= 1)
  150. {
  151. LocalDirectory = CommandParams->Strings[0];
  152. }
  153. else if (!Terminal->SessionData->LocalDirectory.IsEmpty())
  154. {
  155. LocalDirectory = ExpandFileName(Terminal->SessionData->LocalDirectory);
  156. }
  157. else
  158. {
  159. LocalDirectory = WinConfiguration->ScpExplorer.LastLocalTargetDirectory;
  160. }
  161. if (CommandParams->Count >= 2)
  162. {
  163. RemoteDirectory = CommandParams->Strings[1];
  164. }
  165. else
  166. {
  167. RemoteDirectory = Terminal->CurrentDirectory;
  168. }
  169. }
  170. //---------------------------------------------------------------------------
  171. void __fastcall FullSynchronize(TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer,
  172. TStrings * CommandParams, bool UseDefaults)
  173. {
  174. UnicodeString LocalDirectory;
  175. UnicodeString RemoteDirectory;
  176. SynchronizeDirectories(Terminal, CommandParams, LocalDirectory, RemoteDirectory);
  177. bool SaveMode = true;
  178. // bit ugly
  179. TSynchronizeMode Mode = (TSynchronizeMode)GUIConfiguration->SynchronizeMode;
  180. if (ScpExplorer->DoFullSynchronizeDirectories(LocalDirectory,
  181. RemoteDirectory, Mode, SaveMode, UseDefaults))
  182. {
  183. if (SaveMode)
  184. {
  185. GUIConfiguration->SynchronizeMode = Mode;
  186. }
  187. Terminal->CloseOnCompletion();
  188. }
  189. else
  190. {
  191. Abort();
  192. }
  193. }
  194. //---------------------------------------------------------------------------
  195. void __fastcall Synchronize(TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer,
  196. TStrings * CommandParams, bool UseDefaults)
  197. {
  198. UnicodeString LocalDirectory;
  199. UnicodeString RemoteDirectory;
  200. SynchronizeDirectories(Terminal, CommandParams, LocalDirectory, RemoteDirectory);
  201. ScpExplorer->DoSynchronizeDirectories(LocalDirectory, RemoteDirectory, UseDefaults);
  202. Abort();
  203. }
  204. //---------------------------------------------------------------------------
  205. void __fastcall ImportSitesIfAny()
  206. {
  207. if (!WinConfiguration->AutoImportedFromPuttyOrFilezilla)
  208. {
  209. bool AnyPuttySession = GUIConfiguration->AnyPuttySessionForImport(StoredSessions);
  210. bool AnyFilezillaSession = GUIConfiguration->AnyFilezillaSessionForImport(StoredSessions);
  211. if (AnyPuttySession || AnyFilezillaSession)
  212. {
  213. UnicodeString PuttySource = LoadStrPart(IMPORT_SESSIONS2, 2);
  214. UnicodeString FilezillaSource = LoadStrPart(IMPORT_SESSIONS2, 3);
  215. UnicodeString Source;
  216. if (AnyPuttySession && AnyFilezillaSession)
  217. {
  218. Source = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 4), (PuttySource, FilezillaSource));
  219. }
  220. else if (AnyPuttySession)
  221. {
  222. Source = PuttySource;
  223. }
  224. else if (AnyFilezillaSession)
  225. {
  226. Source = FilezillaSource;
  227. }
  228. else
  229. {
  230. DebugFail();
  231. }
  232. UnicodeString Message = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 1), (Source));
  233. if (MessageDialog(Message, qtConfirmation,
  234. qaYes | qaNo, HELP_IMPORT_SESSIONS) == qaYes)
  235. {
  236. DoImportSessionsDialog(NULL);
  237. }
  238. WinConfiguration->AutoImportedFromPuttyOrFilezilla = true;
  239. }
  240. }
  241. }
  242. //---------------------------------------------------------------------------
  243. void __fastcall Usage(UnicodeString Param)
  244. {
  245. while (!Param.IsEmpty())
  246. {
  247. UnicodeString Pair = CutToChar(Param, L',', true);
  248. if (!Pair.IsEmpty())
  249. {
  250. if (Pair[Pair.Length()] == L'+')
  251. {
  252. UnicodeString Key = Pair.SubString(1, Pair.Length() - 1).Trim();
  253. Configuration->Usage->Inc(Key);
  254. }
  255. else
  256. {
  257. UnicodeString Key = CutToChar(Pair, L':', true);
  258. Configuration->Usage->Set(Key, Pair.Trim());
  259. }
  260. }
  261. }
  262. }
  263. //---------------------------------------------------------------------------
  264. void __fastcall RecordWrapperVersions(UnicodeString ConsoleVersion, UnicodeString DotNetVersion)
  265. {
  266. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  267. if (!DotNetVersion.IsEmpty())
  268. {
  269. Updates.DotNetVersion = DotNetVersion;
  270. }
  271. if (!ConsoleVersion.IsEmpty())
  272. {
  273. Updates.ConsoleVersion = ConsoleVersion;
  274. }
  275. WinConfiguration->Updates = Updates;
  276. if (Configuration->Storage == stNul)
  277. {
  278. Configuration->SetDefaultStorage();
  279. try
  280. {
  281. THierarchicalStorage * Storage = Configuration->CreateConfigStorage();
  282. try
  283. {
  284. Storage->AccessMode = smReadWrite;
  285. if (Storage->OpenSubKey(Configuration->ConfigurationSubKey, true) &&
  286. Storage->OpenSubKey(L"Interface\\Updates", true, true))
  287. {
  288. if (!DotNetVersion.IsEmpty())
  289. {
  290. Storage->WriteString(L"DotNetVersion", DotNetVersion);
  291. }
  292. if (!ConsoleVersion.IsEmpty())
  293. {
  294. Storage->WriteString(L"ConsoleVersion", ConsoleVersion);
  295. }
  296. }
  297. }
  298. __finally
  299. {
  300. delete Storage;
  301. }
  302. }
  303. __finally
  304. {
  305. Configuration->SetNulStorage();
  306. }
  307. }
  308. }
  309. //---------------------------------------------------------------------------
  310. static UnicodeString ColorToRGBStr(TColor Color)
  311. {
  312. int RGB = ColorToRGB(Color);
  313. int R = GetRValue(RGB);
  314. int G = GetGValue(RGB);
  315. int B = GetBValue(RGB);
  316. UnicodeString Result = FORMAT(L"%.2x%.2x%.2x", (R, G, B));
  317. return Result;
  318. }
  319. //---------------------------------------------------------------------------
  320. void __fastcall UpdateStaticUsage()
  321. {
  322. Configuration->Usage->Inc(L"Runs");
  323. Configuration->Usage->UpdateCurrentVersion();
  324. UnicodeString WindowsVersion = FORMAT("%d.%d.%d %s", (Win32MajorVersion, Win32MinorVersion, Win32BuildNumber, Win32CSDVersion));
  325. Configuration->Usage->Set(L"WindowsVersion", (WindowsVersion));
  326. Configuration->Usage->Set(L"WindowsProductName", (WindowsProductName()));
  327. DWORD Type;
  328. GetWindowsProductType(Type);
  329. Configuration->Usage->Set(L"WindowsProductType", (static_cast<int>(Type)));
  330. Configuration->Usage->Set(L"Windows64", IsWin64());
  331. Configuration->Usage->Set(L"DefaultLocale",
  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. // We have to check for /console only after the other options,
  604. // as the /console is always used when we are run by winscp.com
  605. // (ambiguous use to pass console version)
  606. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(L"script") ||
  607. Params->FindSwitch(COMMAND_SWITCH))
  608. {
  609. Mode = cmScripting;
  610. }
  611. if (Mode != cmNone)
  612. {
  613. return Console(Mode);
  614. }
  615. TTerminalManager * TerminalManager = NULL;
  616. GlyphsModule = NULL;
  617. NonVisualDataModule = NULL;
  618. TStrings * CommandParams = new TStringList;
  619. try
  620. {
  621. TerminalManager = TTerminalManager::Instance();
  622. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  623. try
  624. {
  625. GlyphsModule = new TGlyphsModule(Application);
  626. }
  627. __finally
  628. {
  629. GUIConfiguration->ChangeResourceModule(ResourceModule);
  630. }
  631. NonVisualDataModule = new TNonVisualDataModule(Application);
  632. LogForm = NULL;
  633. Application->HintHidePause = 3000;
  634. UnicodeString IniFileName = Params->SwitchValue(L"ini");
  635. if (!IniFileName.IsEmpty())
  636. {
  637. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  638. if (!FileExists(ApiPath(IniFileNameExpanded)))
  639. {
  640. // this should be displayed rather at the very beginning.
  641. // however for simplicity (GUI-only), we do it only here.
  642. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  643. }
  644. }
  645. if (Params->FindSwitch(L"UninstallCleanup"))
  646. {
  647. MaintenanceTask();
  648. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  649. // workaround is that we create mutex in uninstaller, if it runs silent, and
  650. // ignore the UninstallCleanup, when the mutex exists.
  651. if ((OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL) &&
  652. (MessageDialog(MainInstructions(LoadStr(UNINSTALL_CLEANUP)), qtConfirmation,
  653. qaYes | qaNo, HELP_UNINSTALL_CLEANUP) == qaYes))
  654. {
  655. DoCleanupDialog(StoredSessions, Configuration);
  656. }
  657. }
  658. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  659. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  660. {
  661. MaintenanceTask();
  662. if (CheckSafe(Params))
  663. {
  664. RegisterForDefaultProtocols();
  665. Configuration->DontSave();
  666. }
  667. }
  668. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  669. {
  670. MaintenanceTask();
  671. if (CheckSafe(Params))
  672. {
  673. UnregisterForProtocols();
  674. Configuration->DontSave();
  675. }
  676. }
  677. else if (Params->FindSwitch(L"AddSearchPath"))
  678. {
  679. MaintenanceTask();
  680. if (CheckSafe(Params))
  681. {
  682. AddSearchPath(ExtractFilePath(Application->ExeName));
  683. Configuration->DontSave();
  684. }
  685. }
  686. else if (Params->FindSwitch(L"RemoveSearchPath"))
  687. {
  688. MaintenanceTask();
  689. if (CheckSafe(Params))
  690. {
  691. try
  692. {
  693. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  694. }
  695. catch(...)
  696. {
  697. // ignore errors
  698. // (RemoveSearchPath is called always on uninstallation,
  699. // even if AddSearchPath was not used, so we would get the error
  700. // always for non-priviledged user)
  701. }
  702. Configuration->DontSave();
  703. }
  704. }
  705. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  706. {
  707. MaintenanceTask();
  708. ImportSitesIfAny();
  709. }
  710. else if (Params->FindSwitch(L"Usage", SwitchValue))
  711. {
  712. MaintenanceTask();
  713. Usage(SwitchValue);
  714. }
  715. else if (Params->FindSwitch(L"Update"))
  716. {
  717. MaintenanceTask();
  718. CheckForUpdates(false);
  719. }
  720. else if (ShowUpdatesIfAvailable())
  721. {
  722. // noop
  723. }
  724. else if (Params->FindSwitch(L"Exit"))
  725. {
  726. // noop
  727. MaintenanceTask();
  728. Configuration->DontSave();
  729. }
  730. else if (Params->FindSwitch(L"MaintenanceTask"))
  731. {
  732. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  733. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  734. MaintenanceTask();
  735. Configuration->DontSave();
  736. }
  737. else
  738. {
  739. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit } ParamCommand;
  740. ParamCommand = pcNone;
  741. UnicodeString AutoStartSession;
  742. UnicodeString DownloadFile;
  743. bool UseDefaults = false;
  744. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  745. if (OnlyInstance &&
  746. WinConfiguration->TemporaryDirectoryCleanup)
  747. {
  748. TemporaryDirectoryCleanup();
  749. }
  750. WinConfiguration->CheckDefaultTranslation();
  751. if (!Params->Empty)
  752. {
  753. if (Params->FindSwitch(L"Defaults") && CheckSafe(Params))
  754. {
  755. UseDefaults = true;
  756. }
  757. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  758. {
  759. ParamCommand = pcUpload;
  760. if (CommandParams->Count == 0)
  761. {
  762. throw Exception(NO_UPLOAD_LIST_ERROR);
  763. }
  764. }
  765. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  766. {
  767. if (CommandParams->Count > 0)
  768. {
  769. ParamCommand = pcUpload;
  770. }
  771. }
  772. else if (Params->FindSwitch(L"Synchronize", CommandParams, 2))
  773. {
  774. ParamCommand = pcFullSynchronize;
  775. }
  776. else if (Params->FindSwitch(L"KeepUpToDate", CommandParams, 2))
  777. {
  778. ParamCommand = pcSynchronize;
  779. }
  780. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  781. (CommandParams->Count == 1))
  782. {
  783. ParamCommand = pcEdit;
  784. }
  785. }
  786. if (Params->ParamCount > 0)
  787. {
  788. if ((ParamCommand == pcNone) &&
  789. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  790. !Params->FindSwitch(NEWINSTANCE_SWICH) &&
  791. SendToAnotherInstance())
  792. {
  793. Configuration->Usage->Inc(L"SendToAnotherInstance");
  794. return 0;
  795. }
  796. AutoStartSession = Params->Param[1];
  797. Params->ParamsProcessed(1, 1);
  798. UnicodeString CounterName;
  799. if (Params->FindSwitch(JUMPLIST_SWITCH))
  800. {
  801. CounterName = L"CommandLineJumpList";
  802. }
  803. else if (Params->FindSwitch(DESKTOP_SWITCH))
  804. {
  805. CounterName = L"CommandLineDesktop";
  806. }
  807. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  808. {
  809. CounterName = L"CommandLineSendToHook";
  810. }
  811. else
  812. {
  813. CounterName = L"CommandLineSession2";
  814. }
  815. Configuration->Usage->Inc(CounterName);
  816. }
  817. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  818. {
  819. AutoStartSession = StoredSessions->Sessions[0]->Name;
  820. }
  821. else
  822. {
  823. AutoStartSession = WinConfiguration->AutoStartSession;
  824. }
  825. // from now flash message boxes on background
  826. SetOnForeground(false);
  827. bool CommandLineOperation = (ParamCommand != pcNone) || !DownloadFile.IsEmpty();
  828. bool NeedSession = CommandLineOperation;
  829. bool Retry;
  830. do
  831. {
  832. Retry = false;
  833. TObjectList * DataList = new TObjectList();
  834. GetLoginData(AutoStartSession, Params, DataList, DownloadFile, NeedSession);
  835. try
  836. {
  837. if (!NeedSession || (DataList->Count > 0))
  838. {
  839. if (CheckSafe(Params))
  840. {
  841. UnicodeString LogFile;
  842. if (Params->FindSwitch(L"Log", LogFile))
  843. {
  844. Configuration->TemporaryLogging(LogFile);
  845. }
  846. if (Params->FindSwitch(L"XmlLog", LogFile))
  847. {
  848. Configuration->TemporaryActionsLogging(LogFile);
  849. }
  850. }
  851. try
  852. {
  853. DebugAssert(!TerminalManager->ActiveTerminal);
  854. bool CanStart;
  855. if (DataList->Count > 0)
  856. {
  857. TerminalManager->ActiveTerminal =
  858. TerminalManager->NewTerminals(DataList);
  859. CanStart = (TerminalManager->Count > 0);
  860. }
  861. else
  862. {
  863. DebugAssert(!NeedSession);
  864. CanStart = true;
  865. }
  866. if (!CanStart)
  867. {
  868. // do not prompt with login dialog, if connection of
  869. // auto-start session (typically from command line) failed
  870. if (AutoStartSession.IsEmpty())
  871. {
  872. Retry = true;
  873. }
  874. }
  875. else
  876. {
  877. // from now on, we do not support runtime interface change
  878. CustomWinConfiguration->CanApplyInterfaceImmediately = false;
  879. TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();
  880. CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;
  881. try
  882. {
  883. // moved inside try .. __finally, because it can fail as well
  884. TerminalManager->ScpExplorer = ScpExplorer;
  885. if (CommandLineOperation)
  886. {
  887. Configuration->Usage->Inc(L"CommandLineOperation");
  888. }
  889. if (ParamCommand == pcUpload)
  890. {
  891. Upload(TerminalManager->ActiveTerminal, CommandParams, UseDefaults);
  892. }
  893. else if (ParamCommand == pcFullSynchronize)
  894. {
  895. FullSynchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  896. CommandParams, UseDefaults);
  897. }
  898. else if (ParamCommand == pcSynchronize)
  899. {
  900. Synchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  901. CommandParams, UseDefaults);
  902. }
  903. else if (ParamCommand == pcEdit)
  904. {
  905. Edit(ScpExplorer, CommandParams);
  906. }
  907. else if (!DownloadFile.IsEmpty())
  908. {
  909. Download(TerminalManager->ActiveTerminal, DownloadFile,
  910. UseDefaults);
  911. }
  912. Application->Run();
  913. }
  914. __finally
  915. {
  916. TerminalManager->ScpExplorer = NULL;
  917. SAFE_DESTROY(ScpExplorer);
  918. }
  919. }
  920. }
  921. catch (Exception &E)
  922. {
  923. ShowExtendedException(&E);
  924. }
  925. }
  926. }
  927. __finally
  928. {
  929. delete DataList;
  930. }
  931. }
  932. while (Retry);
  933. }
  934. }
  935. __finally
  936. {
  937. delete NonVisualDataModule;
  938. NonVisualDataModule = NULL;
  939. delete GlyphsModule;
  940. GlyphsModule = NULL;
  941. TTerminalManager::DestroyInstance();
  942. delete CommandParams;
  943. }
  944. return 0;
  945. }