WinMain.cpp 36 KB

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