WinMain.cpp 35 KB

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