WinMain.cpp 34 KB

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