1
0

WinMain.cpp 37 KB

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