WinMain.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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. IntToHex(static_cast<int>(GetDefaultLCID()), 4));
  332. Configuration->Usage->Set(L"Locale",
  333. IntToHex(static_cast<int>(WinConfiguration->Locale), 4));
  334. Configuration->Usage->Set(L"PixelsPerInch", Screen->PixelsPerInch);
  335. bool PixelsPerInchSystemDiffers = false;
  336. bool PixelsPerInchMonitorsDiffer = false;
  337. bool PixelsPerInchAxesDiffer = false;
  338. HINSTANCE ShCoreLibrary = LoadLibrary(L"shcore.dll");
  339. if (ShCoreLibrary != NULL)
  340. {
  341. GetDpiForMonitorProc GetDpiForMonitor =
  342. (GetDpiForMonitorProc)GetProcAddress(ShCoreLibrary, "GetDpiForMonitor");
  343. if (GetDpiForMonitor != NULL)
  344. {
  345. unsigned int PrimaryDpiX;
  346. unsigned int PrimaryDpiY;
  347. for (int Index = 0; Index < Screen->MonitorCount; Index++)
  348. {
  349. unsigned int DpiX;
  350. unsigned int DpiY;
  351. GetDpiForMonitor(Screen->Monitors[Index]->Handle, MDT_Default, &DpiX, &DpiY);
  352. if (DpiX != DpiY)
  353. {
  354. PixelsPerInchAxesDiffer = true;
  355. }
  356. if (Index == 0)
  357. {
  358. PrimaryDpiX = DpiX;
  359. PrimaryDpiY = DpiY;
  360. // PixelsPerInch is GetDeviceCaps(DC, LOGPIXELSY)
  361. if (DpiY != (unsigned int)Screen->PixelsPerInch)
  362. {
  363. PixelsPerInchSystemDiffers = true;
  364. }
  365. }
  366. else
  367. {
  368. if ((DpiX != PrimaryDpiX) ||
  369. (DpiY != PrimaryDpiY))
  370. {
  371. PixelsPerInchMonitorsDiffer = true;
  372. }
  373. }
  374. }
  375. }
  376. }
  377. if (PixelsPerInchSystemDiffers)
  378. {
  379. Configuration->Usage->Inc(L"PixelsPerInchSystemDiffered");
  380. }
  381. Configuration->Usage->Set(L"PixelsPerInchMonitorsDiffer", PixelsPerInchMonitorsDiffer);
  382. Configuration->Usage->Set(L"PixelsPerInchAxesDiffer", PixelsPerInchAxesDiffer);
  383. Configuration->Usage->Set(L"WorkAreaWidth", Screen->WorkAreaWidth);
  384. Configuration->Usage->Set(L"WorkAreaHeight", Screen->WorkAreaHeight);
  385. HDC DC = GetDC(NULL);
  386. int Planes = GetDeviceCaps(DC, PLANES);
  387. int BitsPixel = GetDeviceCaps(DC, BITSPIXEL);
  388. Configuration->Usage->Set(L"ColorDepth", Planes * BitsPixel);
  389. Configuration->Usage->Set(L"MonitorCount", Screen->MonitorCount);
  390. Configuration->Usage->Set(L"NotUseThemes", !UseThemes());
  391. Configuration->Usage->Set(L"ThemeDefaultFontSize", Application->DefaultFont->Size);
  392. Configuration->Usage->Set(L"ThemeIconFontSize", Screen->IconFont->Size);
  393. Configuration->Usage->Set(L"SysColorWindow", ColorToRGBStr(clWindow));
  394. Configuration->Usage->Set(L"SysColorBtnFace", ColorToRGBStr(clBtnFace));
  395. Configuration->Usage->Set(L"SysColorWindowText", ColorToRGBStr(clWindowText));
  396. UnicodeString ProgramsFolder;
  397. ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);
  398. ProgramsFolder = IncludeTrailingBackslash(ExpandFileName(ProgramsFolder));
  399. UnicodeString ExeName = ExpandFileName(Application->ExeName);
  400. bool InProgramFiles = AnsiSameText(ExeName.SubString(1, ProgramsFolder.Length()), ProgramsFolder);
  401. Configuration->Usage->Set(L"InProgramFiles", InProgramFiles);
  402. Configuration->Usage->Set(L"IsInstalled", IsInstalled());
  403. Configuration->Usage->Set(L"Wine", IsWine());
  404. WinConfiguration->UpdateStaticUsage();
  405. }
  406. //---------------------------------------------------------------------------
  407. void __fastcall MaintenanceTask()
  408. {
  409. CoreMaintenanceTask();
  410. }
  411. //---------------------------------------------------------------------------
  412. struct TFindProcessMainWindowParam
  413. {
  414. unsigned long ProcessId;
  415. HWND HiddenWindow;
  416. HWND MainWindow;
  417. };
  418. //---------------------------------------------------------------------------
  419. BOOL __stdcall FindProcessMainWindow(HWND Handle, LPARAM AParam)
  420. {
  421. TFindProcessMainWindowParam & Param = *reinterpret_cast<TFindProcessMainWindowParam *>(AParam);
  422. unsigned long ProcessId;
  423. if ((Handle != Param.HiddenWindow) &&
  424. (Param.MainWindow == 0) && // optimization
  425. (GetWindowThreadProcessId(Handle, &ProcessId) != 0) &&
  426. (ProcessId == Param.ProcessId))
  427. {
  428. TCopyDataMessage Message;
  429. Message.Version = TCopyDataMessage::Version1;
  430. COPYDATASTRUCT CopyData;
  431. CopyData.cbData = sizeof(Message);
  432. CopyData.lpData = &Message;
  433. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  434. LRESULT SendResult =
  435. SendMessage(Handle, WM_COPYDATA, reinterpret_cast<WPARAM>(HInstance),
  436. reinterpret_cast<LPARAM>(&CopyData));
  437. if (SendResult > 0)
  438. {
  439. Param.MainWindow = Handle;
  440. }
  441. }
  442. return TRUE;
  443. }
  444. //---------------------------------------------------------------------------
  445. bool __fastcall SendToAnotherInstance()
  446. {
  447. HWND HiddenWindow = FindWindow(HIDDEN_WINDOW_NAME, NULL);
  448. bool Result = (HiddenWindow != NULL);
  449. if (Result)
  450. {
  451. TCopyDataMessage Message;
  452. Message.Version = TCopyDataMessage::Version1;
  453. COPYDATASTRUCT CopyData;
  454. CopyData.cbData = sizeof(Message);
  455. CopyData.lpData = &Message;
  456. // this test is actually redundant, it just a kind of optimization to avoid expensive
  457. // EnumWindows, we can achieve the same by testing FindProcessMainWindowParam.MainWindow,
  458. // before sending CommandCommandLine
  459. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  460. LRESULT SendResult =
  461. SendMessage(HiddenWindow, WM_COPYDATA, reinterpret_cast<WPARAM>(HInstance),
  462. reinterpret_cast<LPARAM>(&CopyData));
  463. Result = (SendResult > 0);
  464. if (Result)
  465. {
  466. TFindProcessMainWindowParam FindProcessMainWindowParam;
  467. if (GetWindowThreadProcessId(HiddenWindow, &FindProcessMainWindowParam.ProcessId) != 0)
  468. {
  469. FindProcessMainWindowParam.HiddenWindow = HiddenWindow;
  470. FindProcessMainWindowParam.MainWindow = 0;
  471. if (EnumWindows(FindProcessMainWindow, reinterpret_cast<LPARAM>(&FindProcessMainWindowParam)) &&
  472. (FindProcessMainWindowParam.MainWindow != 0))
  473. {
  474. // Restore window, if minimized
  475. ShowWindow(FindProcessMainWindowParam.MainWindow, SW_RESTORE);
  476. // bring it to foreground
  477. SetForegroundWindow(FindProcessMainWindowParam.MainWindow);
  478. }
  479. }
  480. Message.Command = TCopyDataMessage::CommandCommandLine;
  481. wcsncpy(Message.CommandLine, CmdLine, LENOF(Message.CommandLine));
  482. NULL_TERMINATE(Message.CommandLine);
  483. LRESULT SendResult =
  484. SendMessage(HiddenWindow, WM_COPYDATA,
  485. reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));
  486. Result = (SendResult > 0);
  487. }
  488. }
  489. return Result;
  490. }
  491. //---------------------------------------------------------------------------
  492. bool __fastcall ShowUpdatesIfAvailable()
  493. {
  494. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  495. int CurrentCompoundVer = Configuration->CompoundVersion;
  496. bool NoPopup = true;
  497. bool Result =
  498. Updates.ShowOnStartup &&
  499. Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&
  500. !Updates.Results.Disabled &&
  501. ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&
  502. !Updates.ShownResults;
  503. if (Result)
  504. {
  505. Configuration->Usage->Inc(L"UpdateStartup");
  506. Result = CheckForUpdates(true);
  507. if (Result)
  508. {
  509. Configuration->Usage->Inc(L"UpdateDownloadOpensStartup");
  510. }
  511. NoPopup = false;
  512. }
  513. else if (WinConfiguration->ShowTips)
  514. {
  515. int Days = DaysBetween(WinConfiguration->TipsShown, Now());
  516. if ((Days >= Updates.Results.TipsIntervalDays) &&
  517. (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))
  518. {
  519. UnicodeString Tip = FirstUnshownTip();
  520. if (!Tip.IsEmpty())
  521. {
  522. AutoShowNewTip();
  523. NoPopup = false;
  524. }
  525. else
  526. {
  527. Configuration->Usage->Inc(L"TipsNoUnseen");
  528. }
  529. }
  530. }
  531. if (NoPopup)
  532. {
  533. WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;
  534. }
  535. return Result;
  536. }
  537. //---------------------------------------------------------------------------
  538. int __fastcall Execute()
  539. {
  540. DebugAssert(StoredSessions);
  541. TProgramParams * Params = TProgramParams::Instance();
  542. DebugAssert(Params);
  543. // do not flash message boxes on startup
  544. SetOnForeground(true);
  545. // let installer know, that some instance of application is running
  546. CreateMutex(NULL, False, AppName.c_str());
  547. bool OnlyInstance = (GetLastError() == 0);
  548. UpdateStaticUsage();
  549. UnicodeString KeyFile;
  550. if (Params->FindSwitch(L"PrivateKey", KeyFile))
  551. {
  552. WinConfiguration->DefaultKeyFile = KeyFile;
  553. }
  554. UnicodeString ConsoleVersion;
  555. UnicodeString DotNetVersion;
  556. Params->FindSwitch(L"Console", ConsoleVersion);
  557. Params->FindSwitch(L"DotNet", DotNetVersion);
  558. if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())
  559. {
  560. RecordWrapperVersions(ConsoleVersion, DotNetVersion);
  561. }
  562. if (!DotNetVersion.IsEmpty())
  563. {
  564. Configuration->Usage->Inc(L"ConsoleDotNet");
  565. }
  566. UnicodeString SwitchValue;
  567. if (Params->FindSwitch(L"loglevel", SwitchValue))
  568. {
  569. int StarPos = SwitchValue.Pos(L"*");
  570. if (StarPos > 0)
  571. {
  572. bool LogSensitive = true;
  573. SwitchValue.Delete(StarPos, 1);
  574. if ((StarPos <= SwitchValue.Length()) &&
  575. (SwitchValue[StarPos] == L'-'))
  576. {
  577. LogSensitive = false;
  578. SwitchValue.Delete(StarPos, 1);
  579. }
  580. SwitchValue = SwitchValue.Trim();
  581. Configuration->TemporaryLogSensitive(LogSensitive);
  582. }
  583. int LogProtocol;
  584. if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= 0))
  585. {
  586. Configuration->TemporaryLogProtocol(LogProtocol);
  587. }
  588. }
  589. TConsoleMode Mode = cmNone;
  590. if (Params->FindSwitch(L"help") || Params->FindSwitch(L"h") || Params->FindSwitch(L"?"))
  591. {
  592. Mode = cmHelp;
  593. }
  594. else if (Params->FindSwitch(L"batchsettings"))
  595. {
  596. Mode = cmBatchSettings;
  597. }
  598. else if (Params->FindSwitch(KEYGEN_SWITCH))
  599. {
  600. Mode = cmKeyGen;
  601. }
  602. // We have to check for /console only after the other options,
  603. // as the /console is always used when we are run by winscp.com
  604. // (ambiguous use to pass console version)
  605. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(L"script") ||
  606. Params->FindSwitch(COMMAND_SWITCH))
  607. {
  608. Mode = cmScripting;
  609. }
  610. if (Mode != cmNone)
  611. {
  612. return Console(Mode);
  613. }
  614. TTerminalManager * TerminalManager = NULL;
  615. GlyphsModule = NULL;
  616. NonVisualDataModule = NULL;
  617. TStrings * CommandParams = new TStringList;
  618. try
  619. {
  620. TerminalManager = TTerminalManager::Instance();
  621. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  622. try
  623. {
  624. GlyphsModule = new TGlyphsModule(Application);
  625. }
  626. __finally
  627. {
  628. GUIConfiguration->ChangeResourceModule(ResourceModule);
  629. }
  630. NonVisualDataModule = new TNonVisualDataModule(Application);
  631. LogForm = NULL;
  632. Application->HintHidePause = 3000;
  633. UnicodeString IniFileName = Params->SwitchValue(L"ini");
  634. if (!IniFileName.IsEmpty())
  635. {
  636. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  637. if (!FileExists(ApiPath(IniFileNameExpanded)))
  638. {
  639. // this should be displayed rather at the very beginning.
  640. // however for simplicity (GUI-only), we do it only here.
  641. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  642. }
  643. }
  644. if (Params->FindSwitch(L"UninstallCleanup"))
  645. {
  646. MaintenanceTask();
  647. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  648. // workaround is that we create mutex in uninstaller, if it runs silent, and
  649. // ignore the UninstallCleanup, when the mutex exists.
  650. if ((OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL) &&
  651. (MessageDialog(MainInstructions(LoadStr(UNINSTALL_CLEANUP)), qtConfirmation,
  652. qaYes | qaNo, HELP_UNINSTALL_CLEANUP) == qaYes))
  653. {
  654. DoCleanupDialog(StoredSessions, Configuration);
  655. }
  656. }
  657. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  658. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  659. {
  660. MaintenanceTask();
  661. if (CheckSafe(Params))
  662. {
  663. RegisterForDefaultProtocols();
  664. Configuration->DontSave();
  665. }
  666. }
  667. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  668. {
  669. MaintenanceTask();
  670. if (CheckSafe(Params))
  671. {
  672. UnregisterForProtocols();
  673. Configuration->DontSave();
  674. }
  675. }
  676. else if (Params->FindSwitch(L"AddSearchPath"))
  677. {
  678. MaintenanceTask();
  679. if (CheckSafe(Params))
  680. {
  681. AddSearchPath(ExtractFilePath(Application->ExeName));
  682. Configuration->DontSave();
  683. }
  684. }
  685. else if (Params->FindSwitch(L"RemoveSearchPath"))
  686. {
  687. MaintenanceTask();
  688. if (CheckSafe(Params))
  689. {
  690. try
  691. {
  692. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  693. }
  694. catch(...)
  695. {
  696. // ignore errors
  697. // (RemoveSearchPath is called always on uninstallation,
  698. // even if AddSearchPath was not used, so we would get the error
  699. // always for non-priviledged user)
  700. }
  701. Configuration->DontSave();
  702. }
  703. }
  704. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  705. {
  706. MaintenanceTask();
  707. ImportSitesIfAny();
  708. }
  709. else if (Params->FindSwitch(L"Usage", SwitchValue))
  710. {
  711. MaintenanceTask();
  712. Usage(SwitchValue);
  713. }
  714. else if (Params->FindSwitch(L"Update"))
  715. {
  716. MaintenanceTask();
  717. CheckForUpdates(false);
  718. }
  719. else if (ShowUpdatesIfAvailable())
  720. {
  721. // noop
  722. }
  723. else if (Params->FindSwitch(L"Exit"))
  724. {
  725. // noop
  726. MaintenanceTask();
  727. Configuration->DontSave();
  728. }
  729. else if (Params->FindSwitch(L"MaintenanceTask"))
  730. {
  731. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  732. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  733. MaintenanceTask();
  734. Configuration->DontSave();
  735. }
  736. else
  737. {
  738. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit } ParamCommand;
  739. ParamCommand = pcNone;
  740. UnicodeString AutoStartSession;
  741. UnicodeString DownloadFile;
  742. bool UseDefaults = false;
  743. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  744. if (OnlyInstance &&
  745. WinConfiguration->TemporaryDirectoryCleanup)
  746. {
  747. TemporaryDirectoryCleanup();
  748. }
  749. WinConfiguration->CheckDefaultTranslation();
  750. if (!Params->Empty)
  751. {
  752. if (Params->FindSwitch(L"Defaults") && CheckSafe(Params))
  753. {
  754. UseDefaults = true;
  755. }
  756. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  757. {
  758. ParamCommand = pcUpload;
  759. if (CommandParams->Count == 0)
  760. {
  761. throw Exception(NO_UPLOAD_LIST_ERROR);
  762. }
  763. }
  764. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  765. {
  766. if (CommandParams->Count > 0)
  767. {
  768. ParamCommand = pcUpload;
  769. }
  770. }
  771. else if (Params->FindSwitch(L"Synchronize", CommandParams, 2))
  772. {
  773. ParamCommand = pcFullSynchronize;
  774. }
  775. else if (Params->FindSwitch(L"KeepUpToDate", CommandParams, 2))
  776. {
  777. ParamCommand = pcSynchronize;
  778. }
  779. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  780. (CommandParams->Count == 1))
  781. {
  782. ParamCommand = pcEdit;
  783. }
  784. }
  785. if (Params->ParamCount > 0)
  786. {
  787. if ((ParamCommand == pcNone) &&
  788. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  789. !Params->FindSwitch(NEWINSTANCE_SWICH) &&
  790. SendToAnotherInstance())
  791. {
  792. Configuration->Usage->Inc(L"SendToAnotherInstance");
  793. return 0;
  794. }
  795. AutoStartSession = Params->Param[1];
  796. Params->ParamsProcessed(1, 1);
  797. UnicodeString CounterName;
  798. if (Params->FindSwitch(JUMPLIST_SWITCH))
  799. {
  800. CounterName = L"CommandLineJumpList";
  801. }
  802. else if (Params->FindSwitch(DESKTOP_SWITCH))
  803. {
  804. CounterName = L"CommandLineDesktop";
  805. }
  806. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  807. {
  808. CounterName = L"CommandLineSendToHook";
  809. }
  810. else
  811. {
  812. CounterName = L"CommandLineSession2";
  813. }
  814. Configuration->Usage->Inc(CounterName);
  815. }
  816. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  817. {
  818. AutoStartSession = StoredSessions->Sessions[0]->Name;
  819. }
  820. else
  821. {
  822. AutoStartSession = WinConfiguration->AutoStartSession;
  823. }
  824. // from now flash message boxes on background
  825. SetOnForeground(false);
  826. bool CommandLineOperation = (ParamCommand != pcNone) || !DownloadFile.IsEmpty();
  827. bool NeedSession = CommandLineOperation;
  828. bool Retry;
  829. do
  830. {
  831. Retry = false;
  832. TObjectList * DataList = new TObjectList();
  833. try
  834. {
  835. GetLoginData(AutoStartSession, Params, DataList, DownloadFile, NeedSession);
  836. // GetLoginData now Aborts when session is needed and none is selected
  837. if (DebugAlwaysTrue(!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. ReleaseAnimationsModule();
  940. delete GlyphsModule;
  941. GlyphsModule = NULL;
  942. TTerminalManager::DestroyInstance();
  943. delete CommandParams;
  944. }
  945. return 0;
  946. }