WinMain.cpp 37 KB

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