WinMain.cpp 36 KB

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