WinMain.cpp 35 KB

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