WinMain.cpp 36 KB

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