WinMain.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <CoreMain.h>
  5. #include <TextsWin.h>
  6. #include <TextsCore.h>
  7. #include <HelpWin.h>
  8. #include "CustomScpExplorer.h"
  9. #include "TerminalManager.h"
  10. #include "NonVisual.h"
  11. #include "Glyphs.h"
  12. #include "ProgParams.h"
  13. #include "Setup.h"
  14. #include "WinConfiguration.h"
  15. #include "GUITools.h"
  16. #include "Tools.h"
  17. #include "WinApi.h"
  18. #include <DateUtils.hpp>
  19. //---------------------------------------------------------------------------
  20. #pragma package(smart_init)
  21. //---------------------------------------------------------------------------
  22. void __fastcall GetLoginData(UnicodeString SessionName, TOptions * Options,
  23. TObjectList * DataList, UnicodeString & DownloadFile, bool NeedSession, TForm * LinkedForm)
  24. {
  25. bool DefaultsOnly = false;
  26. if (StoredSessions->IsFolder(SessionName) ||
  27. StoredSessions->IsWorkspace(SessionName))
  28. {
  29. StoredSessions->GetFolderOrWorkspace(SessionName, DataList);
  30. }
  31. else
  32. {
  33. TSessionData * SessionData =
  34. StoredSessions->ParseUrl(SessionName, Options, DefaultsOnly,
  35. &DownloadFile);
  36. DataList->Add(SessionData);
  37. if (DataList->Count == 1)
  38. {
  39. TSessionData * SessionData = DebugNotNull(dynamic_cast<TSessionData *>(DataList->Items[0]));
  40. if (SessionData->SaveOnly)
  41. {
  42. Configuration->Usage->Inc(L"CommandLineSessionSave");
  43. TSessionData * SavedSession = DoSaveSession(SessionData, NULL, true, NULL);
  44. if (SavedSession == NULL)
  45. {
  46. Abort();
  47. }
  48. WinConfiguration->LastStoredSession = SavedSession->Name;
  49. DataList->Clear();
  50. }
  51. else if (!SessionData->PuttyProtocol.IsEmpty())
  52. {
  53. // putty does not support resolving environment variables in session settings
  54. // though it's hardly of any use here.
  55. SessionData->ExpandEnvironmentVariables();
  56. OpenSessionInPutty(GUIConfiguration->PuttyPath, SessionData);
  57. Abort();
  58. }
  59. }
  60. }
  61. if (DefaultsOnly && !NeedSession)
  62. {
  63. // No URL specified on command-line and no explicit command-line parameter
  64. // that requires session was specified => noop
  65. DataList->Clear();
  66. }
  67. else if ((DataList->Count == 0) ||
  68. !dynamic_cast<TSessionData *>(DataList->Items[0])->CanLogin ||
  69. DefaultsOnly)
  70. {
  71. // Note that GetFolderOrWorkspace never returns sites that !CanLogin,
  72. // so we should not get here with more then one site.
  73. // Though we should be good, if we ever do.
  74. // We get here when:
  75. // - we need session for explicit command-line operation
  76. // - after we handle "save" URL.
  77. // - the specified session does not contain enough information to login [= not even hostname]
  78. DebugAssert(DataList->Count <= 1);
  79. if (!DoLoginDialog(StoredSessions, DataList, LinkedForm))
  80. {
  81. Abort();
  82. }
  83. }
  84. }
  85. //---------------------------------------------------------------------------
  86. void __fastcall Upload(TTerminal * Terminal, TStrings * FileList, bool UseDefaults)
  87. {
  88. UnicodeString TargetDirectory;
  89. TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;
  90. TargetDirectory = UnixIncludeTrailingBackslash(Terminal->CurrentDirectory);
  91. std::unique_ptr<TSessionData> Data(Terminal->SessionData->Clone());
  92. Terminal->FillSessionDataForCode(Data.get());
  93. int Options = coDisableQueue;
  94. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  95. if (UseDefaults ||
  96. DoCopyDialog(true, false, FileList, TargetDirectory, &CopyParam, Options,
  97. CopyParamAttrs, Data.get(), NULL))
  98. {
  99. Terminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, 0, NULL);
  100. }
  101. }
  102. //---------------------------------------------------------------------------
  103. void __fastcall Download(TTerminal * Terminal, const UnicodeString FileName,
  104. bool UseDefaults)
  105. {
  106. TRemoteFile * File = NULL;
  107. try
  108. {
  109. Terminal->ExceptionOnFail = true;
  110. try
  111. {
  112. Terminal->ReadFile(FileName, File);
  113. }
  114. __finally
  115. {
  116. Terminal->ExceptionOnFail = false;
  117. }
  118. File->FullFileName = FileName;
  119. UnicodeString LocalDirectory = ExpandFileName(Terminal->SessionData->LocalDirectory);
  120. if (LocalDirectory.IsEmpty())
  121. {
  122. LocalDirectory = GetPersonalFolder();
  123. }
  124. UnicodeString TargetDirectory = IncludeTrailingBackslash(LocalDirectory);
  125. TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;
  126. UnicodeString DisplayName = File->FileName;
  127. bool CustomDisplayName =
  128. !File->DisplayName.IsEmpty() &&
  129. (File->DisplayName != DisplayName);
  130. if (CustomDisplayName)
  131. {
  132. DisplayName = File->DisplayName;
  133. }
  134. UnicodeString FriendyFileName = UnixIncludeTrailingBackslash(UnixExtractFilePath(FileName)) + DisplayName;
  135. std::unique_ptr<TStrings> FileListFriendly(new TStringList());
  136. FileListFriendly->AddObject(FriendyFileName, File);
  137. int Options = coDisableQueue;
  138. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Download;
  139. if (UseDefaults ||
  140. DoCopyDialog(false, false, FileListFriendly.get(), TargetDirectory, &CopyParam,
  141. Options, CopyParamAttrs, NULL, NULL))
  142. {
  143. if (CustomDisplayName)
  144. {
  145. // Set only now, so that it is not redundantly displayed on the copy dialog.
  146. // We should escape the * and ?'s.
  147. CopyParam.FileMask = DisplayName;
  148. }
  149. std::unique_ptr<TStrings> FileList(new TStringList());
  150. FileList->AddObject(FileName, File);
  151. Terminal->CopyToLocal(FileList.get(), TargetDirectory, &CopyParam, 0, NULL);
  152. }
  153. UnicodeString Directory = UnixExtractFilePath(FileName);
  154. Terminal->AutoReadDirectory = true;
  155. Terminal->ChangeDirectory(Directory);
  156. }
  157. __finally
  158. {
  159. delete File;
  160. }
  161. }
  162. //---------------------------------------------------------------------------
  163. void __fastcall Edit(TCustomScpExplorerForm * ScpExplorer, TStrings * FileList)
  164. {
  165. ScpExplorer->StandaloneEdit(FileList->Strings[0]);
  166. Abort();
  167. }
  168. //---------------------------------------------------------------------------
  169. void __fastcall SynchronizeDirectories(TTerminal * Terminal,
  170. TStrings * CommandParams,
  171. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory)
  172. {
  173. if (CommandParams->Count >= 1)
  174. {
  175. LocalDirectory = CommandParams->Strings[0];
  176. }
  177. else if (!Terminal->SessionData->LocalDirectory.IsEmpty())
  178. {
  179. LocalDirectory = ExpandFileName(Terminal->SessionData->LocalDirectory);
  180. }
  181. else
  182. {
  183. LocalDirectory = WinConfiguration->ScpExplorer.LastLocalTargetDirectory;
  184. }
  185. if (CommandParams->Count >= 2)
  186. {
  187. RemoteDirectory = CommandParams->Strings[1];
  188. }
  189. else
  190. {
  191. RemoteDirectory = Terminal->CurrentDirectory;
  192. }
  193. }
  194. //---------------------------------------------------------------------------
  195. void __fastcall FullSynchronize(TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer,
  196. TStrings * CommandParams, bool UseDefaults)
  197. {
  198. UnicodeString LocalDirectory;
  199. UnicodeString RemoteDirectory;
  200. SynchronizeDirectories(Terminal, CommandParams, LocalDirectory, RemoteDirectory);
  201. bool SaveMode = true;
  202. // bit ugly
  203. TSynchronizeMode Mode = (TSynchronizeMode)GUIConfiguration->SynchronizeMode;
  204. if (ScpExplorer->DoFullSynchronizeDirectories(LocalDirectory,
  205. RemoteDirectory, Mode, SaveMode, UseDefaults))
  206. {
  207. if (SaveMode)
  208. {
  209. GUIConfiguration->SynchronizeMode = Mode;
  210. }
  211. Terminal->CloseOnCompletion();
  212. }
  213. else
  214. {
  215. Abort();
  216. }
  217. }
  218. //---------------------------------------------------------------------------
  219. void __fastcall Synchronize(TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer,
  220. TStrings * CommandParams, bool UseDefaults)
  221. {
  222. UnicodeString LocalDirectory;
  223. UnicodeString RemoteDirectory;
  224. SynchronizeDirectories(Terminal, CommandParams, LocalDirectory, RemoteDirectory);
  225. ScpExplorer->DoSynchronizeDirectories(LocalDirectory, RemoteDirectory, UseDefaults);
  226. Abort();
  227. }
  228. //---------------------------------------------------------------------------
  229. void __fastcall ImportSitesIfAny()
  230. {
  231. if (!WinConfiguration->AutoImportedFromPuttyOrFilezilla)
  232. {
  233. bool AnyPuttySession = GUIConfiguration->AnyPuttySessionForImport(StoredSessions);
  234. bool AnyFilezillaSession = GUIConfiguration->AnyFilezillaSessionForImport(StoredSessions);
  235. if (AnyPuttySession || AnyFilezillaSession)
  236. {
  237. UnicodeString PuttySource = LoadStrPart(IMPORT_SESSIONS2, 2);
  238. UnicodeString FilezillaSource = LoadStrPart(IMPORT_SESSIONS2, 3);
  239. UnicodeString Source;
  240. if (AnyPuttySession && AnyFilezillaSession)
  241. {
  242. Source = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 4), (PuttySource, FilezillaSource));
  243. }
  244. else if (AnyPuttySession)
  245. {
  246. Source = PuttySource;
  247. }
  248. else if (AnyFilezillaSession)
  249. {
  250. Source = FilezillaSource;
  251. }
  252. else
  253. {
  254. DebugFail();
  255. }
  256. UnicodeString Message = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 1), (Source));
  257. if (MessageDialog(Message, qtConfirmation,
  258. qaYes | qaNo, HELP_IMPORT_SESSIONS) == qaYes)
  259. {
  260. DoImportSessionsDialog(NULL);
  261. }
  262. WinConfiguration->AutoImportedFromPuttyOrFilezilla = true;
  263. }
  264. }
  265. }
  266. //---------------------------------------------------------------------------
  267. void __fastcall Usage(UnicodeString Param)
  268. {
  269. while (!Param.IsEmpty())
  270. {
  271. UnicodeString Pair = CutToChar(Param, L',', true);
  272. if (!Pair.IsEmpty())
  273. {
  274. if (Pair[Pair.Length()] == L'+')
  275. {
  276. UnicodeString Key = Pair.SubString(1, Pair.Length() - 1).Trim();
  277. Configuration->Usage->Inc(Key);
  278. }
  279. else
  280. {
  281. UnicodeString Key = CutToChar(Pair, L':', true);
  282. Configuration->Usage->Set(Key, Pair.Trim());
  283. }
  284. }
  285. }
  286. }
  287. //---------------------------------------------------------------------------
  288. void __fastcall RecordWrapperVersions(UnicodeString ConsoleVersion, UnicodeString DotNetVersion)
  289. {
  290. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  291. if (!DotNetVersion.IsEmpty())
  292. {
  293. Updates.DotNetVersion = DotNetVersion;
  294. }
  295. if (!ConsoleVersion.IsEmpty())
  296. {
  297. Updates.ConsoleVersion = ConsoleVersion;
  298. }
  299. WinConfiguration->Updates = Updates;
  300. if (Configuration->Storage == stNul)
  301. {
  302. Configuration->SetDefaultStorage();
  303. try
  304. {
  305. THierarchicalStorage * Storage = Configuration->CreateConfigStorage();
  306. try
  307. {
  308. Storage->AccessMode = smReadWrite;
  309. if (Storage->OpenSubKey(Configuration->ConfigurationSubKey, true) &&
  310. Storage->OpenSubKey(L"Interface\\Updates", true, true))
  311. {
  312. if (!DotNetVersion.IsEmpty())
  313. {
  314. Storage->WriteString(L"DotNetVersion", DotNetVersion);
  315. }
  316. if (!ConsoleVersion.IsEmpty())
  317. {
  318. Storage->WriteString(L"ConsoleVersion", ConsoleVersion);
  319. }
  320. }
  321. }
  322. __finally
  323. {
  324. delete Storage;
  325. }
  326. }
  327. __finally
  328. {
  329. Configuration->SetNulStorage();
  330. }
  331. }
  332. }
  333. //---------------------------------------------------------------------------
  334. static UnicodeString ColorToRGBStr(TColor Color)
  335. {
  336. int RGB = ColorToRGB(Color);
  337. int R = GetRValue(RGB);
  338. int G = GetGValue(RGB);
  339. int B = GetBValue(RGB);
  340. UnicodeString Result = FORMAT(L"%.2x%.2x%.2x", (R, G, B));
  341. return Result;
  342. }
  343. //---------------------------------------------------------------------------
  344. void __fastcall UpdateStaticUsage()
  345. {
  346. Configuration->Usage->Inc(L"Runs");
  347. Configuration->Usage->UpdateCurrentVersion();
  348. Configuration->Usage->Set(L"WindowsVersion", (WindowsVersionLong()));
  349. Configuration->Usage->Set(L"WindowsProductName", (WindowsProductName()));
  350. DWORD Type;
  351. GetWindowsProductType(Type);
  352. Configuration->Usage->Set(L"WindowsProductType", (static_cast<int>(Type)));
  353. Configuration->Usage->Set(L"Windows64", IsWin64());
  354. Configuration->Usage->Set(L"DefaultLocale",
  355. // See TGUIConfiguration::GetAppliedLocaleHex()
  356. IntToHex(static_cast<int>(GetDefaultLCID()), 4));
  357. Configuration->Usage->Set(L"Locale", WinConfiguration->AppliedLocaleHex);
  358. Configuration->Usage->Set(L"PixelsPerInch", Screen->PixelsPerInch);
  359. bool PixelsPerInchSystemDiffers = false;
  360. bool PixelsPerInchMonitorsDiffer = false;
  361. bool PixelsPerInchAxesDiffer = false;
  362. HINSTANCE ShCoreLibrary = LoadLibrary(L"shcore.dll");
  363. if (ShCoreLibrary != NULL)
  364. {
  365. GetDpiForMonitorProc GetDpiForMonitor =
  366. (GetDpiForMonitorProc)GetProcAddress(ShCoreLibrary, "GetDpiForMonitor");
  367. if (GetDpiForMonitor != NULL)
  368. {
  369. unsigned int PrimaryDpiX;
  370. unsigned int PrimaryDpiY;
  371. for (int Index = 0; Index < Screen->MonitorCount; Index++)
  372. {
  373. unsigned int DpiX;
  374. unsigned int DpiY;
  375. GetDpiForMonitor(Screen->Monitors[Index]->Handle, MDT_Default, &DpiX, &DpiY);
  376. if (DpiX != DpiY)
  377. {
  378. PixelsPerInchAxesDiffer = true;
  379. }
  380. if (Index == 0)
  381. {
  382. PrimaryDpiX = DpiX;
  383. PrimaryDpiY = DpiY;
  384. // PixelsPerInch is GetDeviceCaps(DC, LOGPIXELSY)
  385. if (DpiY != (unsigned int)Screen->PixelsPerInch)
  386. {
  387. PixelsPerInchSystemDiffers = true;
  388. }
  389. }
  390. else
  391. {
  392. if ((DpiX != PrimaryDpiX) ||
  393. (DpiY != PrimaryDpiY))
  394. {
  395. PixelsPerInchMonitorsDiffer = true;
  396. }
  397. }
  398. }
  399. }
  400. }
  401. if (PixelsPerInchSystemDiffers)
  402. {
  403. Configuration->Usage->Inc(L"PixelsPerInchSystemDiffered");
  404. }
  405. Configuration->Usage->Set(L"PixelsPerInchMonitorsDiffer", PixelsPerInchMonitorsDiffer);
  406. Configuration->Usage->Set(L"PixelsPerInchAxesDiffer", PixelsPerInchAxesDiffer);
  407. Configuration->Usage->Set(L"WorkAreaWidth", Screen->WorkAreaWidth);
  408. Configuration->Usage->Set(L"WorkAreaHeight", Screen->WorkAreaHeight);
  409. HDC DC = GetDC(NULL);
  410. int Planes = GetDeviceCaps(DC, PLANES);
  411. int BitsPixel = GetDeviceCaps(DC, BITSPIXEL);
  412. Configuration->Usage->Set(L"ColorDepth", Planes * BitsPixel);
  413. Configuration->Usage->Set(L"MonitorCount", Screen->MonitorCount);
  414. Configuration->Usage->Set(L"NotUseThemes", !UseThemes());
  415. Configuration->Usage->Set(L"ThemeDefaultFontSize", Application->DefaultFont->Size);
  416. Configuration->Usage->Set(L"ThemeIconFontSize", Screen->IconFont->Size);
  417. Configuration->Usage->Set(L"SysColorWindow", ColorToRGBStr(clWindow));
  418. Configuration->Usage->Set(L"SysColorBtnFace", ColorToRGBStr(clBtnFace));
  419. Configuration->Usage->Set(L"SysColorWindowText", ColorToRGBStr(clWindowText));
  420. UnicodeString ProgramsFolder;
  421. ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);
  422. ProgramsFolder = IncludeTrailingBackslash(ExpandFileName(ProgramsFolder));
  423. UnicodeString ExeName = ExpandFileName(Application->ExeName);
  424. bool InProgramFiles = AnsiSameText(ExeName.SubString(1, ProgramsFolder.Length()), ProgramsFolder);
  425. Configuration->Usage->Set(L"InProgramFiles", InProgramFiles);
  426. Configuration->Usage->Set(L"IsInstalled", IsInstalled());
  427. Configuration->Usage->Set(L"Wine", IsWine());
  428. Configuration->Usage->Set(L"NetFrameworkVersion", GetNetVersionStr());
  429. Configuration->Usage->Set(L"PowerShellVersion", GetPowerShellVersionStr());
  430. WinConfiguration->UpdateStaticUsage();
  431. }
  432. //---------------------------------------------------------------------------
  433. void __fastcall MaintenanceTask()
  434. {
  435. CoreMaintenanceTask();
  436. }
  437. //---------------------------------------------------------------------------
  438. typedef std::vector<HWND> THandles;
  439. typedef std::map<unsigned long, THandles> TProcesses;
  440. //---------------------------------------------------------------------------
  441. BOOL __stdcall EnumOtherInstances(HWND Handle, LPARAM AParam)
  442. {
  443. TProcesses & Processes = *reinterpret_cast<TProcesses *>(AParam);
  444. unsigned long ProcessId;
  445. if (GetWindowThreadProcessId(Handle, &ProcessId) != 0)
  446. {
  447. Processes[ProcessId].push_back(Handle);
  448. }
  449. return TRUE;
  450. }
  451. //---------------------------------------------------------------------------
  452. static bool __fastcall SendCopyDataMessage(HWND Window, TCopyDataMessage & Message)
  453. {
  454. COPYDATASTRUCT CopyData;
  455. CopyData.cbData = sizeof(Message);
  456. CopyData.lpData = &Message;
  457. LRESULT SendResult =
  458. SendMessage(Window, WM_COPYDATA,
  459. reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));
  460. bool Result = (SendResult > 0);
  461. return Result;
  462. }
  463. //---------------------------------------------------------------------------
  464. static void __fastcall FindOtherInstances(THandles & OtherInstances)
  465. {
  466. TProcesses Processes;
  467. // FindWindow is optimization (if there's no hidden window, no point enumerating all windows to find some)
  468. if ((FindWindow(HIDDEN_WINDOW_NAME, NULL) != NULL) &&
  469. EnumWindows(EnumOtherInstances, reinterpret_cast<LPARAM>(&Processes)))
  470. {
  471. TCopyDataMessage Message;
  472. Message.Command = TCopyDataMessage::MainWindowCheck;
  473. TProcesses::const_iterator ProcessI = Processes.begin();
  474. while (ProcessI != Processes.end())
  475. {
  476. HWND HiddenWindow = NULL;
  477. THandles::const_iterator WindowI = ProcessI->second.begin();
  478. while ((HiddenWindow == NULL) && (WindowI != ProcessI->second.end()))
  479. {
  480. wchar_t ClassName[1024];
  481. if (GetClassName(*WindowI, ClassName, LENOF(ClassName)) != 0)
  482. {
  483. NULL_TERMINATE(ClassName);
  484. if (wcscmp(ClassName, HIDDEN_WINDOW_NAME) == 0)
  485. {
  486. HiddenWindow = *WindowI;
  487. }
  488. }
  489. WindowI++;
  490. }
  491. if (HiddenWindow != NULL)
  492. {
  493. WindowI = ProcessI->second.begin();
  494. while (WindowI != ProcessI->second.end())
  495. {
  496. if (*WindowI != HiddenWindow) // optimization
  497. {
  498. if (SendCopyDataMessage(*WindowI, Message))
  499. {
  500. OtherInstances.push_back(*WindowI);
  501. break;
  502. }
  503. }
  504. WindowI++;
  505. }
  506. }
  507. ProcessI++;
  508. }
  509. }
  510. }
  511. //---------------------------------------------------------------------------
  512. bool __fastcall SendToAnotherInstance()
  513. {
  514. THandles OtherInstances;
  515. FindOtherInstances(OtherInstances);
  516. bool Result = false;
  517. THandles::const_iterator I = OtherInstances.begin();
  518. while (!Result && (I != OtherInstances.end()))
  519. {
  520. HWND Handle = *I;
  521. TCopyDataMessage Message;
  522. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  523. if (SendCopyDataMessage(Handle, Message))
  524. {
  525. // Restore window, if minimized
  526. ShowWindow(Handle, SW_RESTORE);
  527. // bring it to foreground
  528. SetForegroundWindow(Handle);
  529. Message.Command = TCopyDataMessage::CommandCommandLine;
  530. wcsncpy(Message.CommandLine, CmdLine, LENOF(Message.CommandLine));
  531. NULL_TERMINATE(Message.CommandLine);
  532. Result = SendCopyDataMessage(Handle, Message);
  533. }
  534. I++;
  535. }
  536. return Result;
  537. }
  538. //---------------------------------------------------------------------------
  539. void __fastcall Refresh(const UnicodeString & Session, const UnicodeString & Path)
  540. {
  541. THandles OtherInstances;
  542. FindOtherInstances(OtherInstances);
  543. THandles::const_iterator I = OtherInstances.begin();
  544. while (I != OtherInstances.end())
  545. {
  546. HWND Handle = *I;
  547. TCopyDataMessage Message;
  548. Message.Command = TCopyDataMessage::RefreshPanel;
  549. wcsncpy(Message.Refresh.Session, Session.c_str(), LENOF(Message.Refresh.Session));
  550. NULL_TERMINATE(Message.Refresh.Session);
  551. wcsncpy(Message.Refresh.Path, Path.c_str(), LENOF(Message.Refresh.Path));
  552. NULL_TERMINATE(Message.Refresh.Path);
  553. SendCopyDataMessage(Handle, Message);
  554. I++;
  555. }
  556. }
  557. //---------------------------------------------------------------------------
  558. bool __fastcall ShowUpdatesIfAvailable()
  559. {
  560. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  561. int CurrentCompoundVer = Configuration->CompoundVersion;
  562. bool NoPopup = true;
  563. bool Result =
  564. Updates.ShowOnStartup &&
  565. Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&
  566. !Updates.Results.Disabled &&
  567. ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&
  568. !Updates.ShownResults;
  569. if (Result)
  570. {
  571. Configuration->Usage->Inc(L"UpdateStartup");
  572. Result = CheckForUpdates(true);
  573. if (Result)
  574. {
  575. Configuration->Usage->Inc(L"UpdateDownloadOpensStartup");
  576. }
  577. NoPopup = false;
  578. }
  579. else if (WinConfiguration->ShowTips)
  580. {
  581. int Days = DaysBetween(WinConfiguration->TipsShown, Now());
  582. if ((Days >= Updates.Results.TipsIntervalDays) &&
  583. (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))
  584. {
  585. UnicodeString Tip = FirstUnshownTip();
  586. if (!Tip.IsEmpty())
  587. {
  588. AutoShowNewTip();
  589. NoPopup = false;
  590. }
  591. else
  592. {
  593. Configuration->Usage->Inc(L"TipsNoUnseen");
  594. }
  595. }
  596. }
  597. if (NoPopup)
  598. {
  599. WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;
  600. }
  601. return Result;
  602. }
  603. //---------------------------------------------------------------------------
  604. int __fastcall Execute()
  605. {
  606. DebugAssert(StoredSessions);
  607. TProgramParams * Params = TProgramParams::Instance();
  608. DebugAssert(Params);
  609. // do not flash message boxes on startup
  610. SetOnForeground(true);
  611. // let installer know, that some instance of application is running
  612. CreateMutex(NULL, False, AppName.c_str());
  613. bool OnlyInstance = (GetLastError() == 0);
  614. UpdateStaticUsage();
  615. UnicodeString KeyFile;
  616. if (Params->FindSwitch(L"PrivateKey", KeyFile))
  617. {
  618. WinConfiguration->DefaultKeyFile = KeyFile;
  619. }
  620. UnicodeString ConsoleVersion;
  621. UnicodeString DotNetVersion;
  622. Params->FindSwitch(L"Console", ConsoleVersion);
  623. Params->FindSwitch(L"DotNet", DotNetVersion);
  624. if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())
  625. {
  626. RecordWrapperVersions(ConsoleVersion, DotNetVersion);
  627. }
  628. if (!DotNetVersion.IsEmpty())
  629. {
  630. Configuration->Usage->Inc(L"ConsoleDotNet");
  631. }
  632. UnicodeString SwitchValue;
  633. if (Params->FindSwitch(L"loglevel", SwitchValue))
  634. {
  635. int StarPos = SwitchValue.Pos(L"*");
  636. if (StarPos > 0)
  637. {
  638. bool LogSensitive = true;
  639. SwitchValue.Delete(StarPos, 1);
  640. if ((StarPos <= SwitchValue.Length()) &&
  641. (SwitchValue[StarPos] == L'-'))
  642. {
  643. LogSensitive = false;
  644. SwitchValue.Delete(StarPos, 1);
  645. }
  646. SwitchValue = SwitchValue.Trim();
  647. Configuration->TemporaryLogSensitive(LogSensitive);
  648. }
  649. int LogProtocol;
  650. if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= 0))
  651. {
  652. Configuration->TemporaryLogProtocol(LogProtocol);
  653. }
  654. }
  655. if (Params->FindSwitch(LOGSIZE_SWITCH, SwitchValue))
  656. {
  657. int StarPos = SwitchValue.Pos(LOGSIZE_SEPARATOR);
  658. int LogMaxCount = 0;
  659. if (StarPos > 1)
  660. {
  661. if (!TryStrToInt(SwitchValue.SubString(1, StarPos - 1), LogMaxCount))
  662. {
  663. LogMaxCount = -1;
  664. }
  665. SwitchValue.Delete(1, StarPos);
  666. SwitchValue = SwitchValue.Trim();
  667. }
  668. __int64 LogMaxSize;
  669. if ((LogMaxCount >= 0) &&
  670. !SwitchValue.IsEmpty() &&
  671. TryStrToSize(SwitchValue, LogMaxSize))
  672. {
  673. Configuration->TemporaryLogMaxCount(LogMaxCount);
  674. Configuration->TemporaryLogMaxSize(LogMaxSize);
  675. }
  676. }
  677. TConsoleMode Mode = cmNone;
  678. if (Params->FindSwitch(L"help") || Params->FindSwitch(L"h") || Params->FindSwitch(L"?"))
  679. {
  680. Mode = cmHelp;
  681. }
  682. else if (Params->FindSwitch(L"batchsettings"))
  683. {
  684. Mode = cmBatchSettings;
  685. }
  686. else if (Params->FindSwitch(KEYGEN_SWITCH))
  687. {
  688. Mode = cmKeyGen;
  689. }
  690. else if (Params->FindSwitch(FINGERPRINTSCAN_SWITCH))
  691. {
  692. Mode = cmFingerprintScan;
  693. }
  694. // We have to check for /console only after the other options,
  695. // as the /console is always used when we are run by winscp.com
  696. // (ambiguous use to pass console version)
  697. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(SCRIPT_SWITCH) ||
  698. Params->FindSwitch(COMMAND_SWITCH))
  699. {
  700. Mode = cmScripting;
  701. }
  702. if (Mode != cmNone)
  703. {
  704. return Console(Mode);
  705. }
  706. TTerminalManager * TerminalManager = NULL;
  707. GlyphsModule = NULL;
  708. NonVisualDataModule = NULL;
  709. TStrings * CommandParams = new TStringList;
  710. try
  711. {
  712. TerminalManager = TTerminalManager::Instance();
  713. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  714. try
  715. {
  716. GlyphsModule = new TGlyphsModule(Application);
  717. }
  718. __finally
  719. {
  720. GUIConfiguration->ChangeResourceModule(ResourceModule);
  721. }
  722. NonVisualDataModule = new TNonVisualDataModule(Application);
  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. }