WinMain.cpp 37 KB

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