WinMain.cpp 37 KB

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