WinMain.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  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. if (Params->FindSwitch(LOGSIZE_SWITCH, SwitchValue))
  631. {
  632. int StarPos = SwitchValue.Pos(LOGSIZE_SEPARATOR);
  633. int LogMaxCount = 0;
  634. if (StarPos > 1)
  635. {
  636. if (!TryStrToInt(SwitchValue.SubString(1, StarPos - 1), LogMaxCount))
  637. {
  638. LogMaxCount = -1;
  639. }
  640. SwitchValue.Delete(1, StarPos);
  641. SwitchValue = SwitchValue.Trim();
  642. }
  643. __int64 LogMaxSize;
  644. if ((LogMaxCount >= 0) &&
  645. !SwitchValue.IsEmpty() &&
  646. TryStrToSize(SwitchValue, LogMaxSize))
  647. {
  648. Configuration->TemporaryLogMaxCount(LogMaxCount);
  649. Configuration->TemporaryLogMaxSize(LogMaxSize);
  650. }
  651. }
  652. TConsoleMode Mode = cmNone;
  653. if (Params->FindSwitch(L"help") || Params->FindSwitch(L"h") || Params->FindSwitch(L"?"))
  654. {
  655. Mode = cmHelp;
  656. }
  657. else if (Params->FindSwitch(L"batchsettings"))
  658. {
  659. Mode = cmBatchSettings;
  660. }
  661. else if (Params->FindSwitch(KEYGEN_SWITCH))
  662. {
  663. Mode = cmKeyGen;
  664. }
  665. else if (Params->FindSwitch(FINGERPRINTSCAN_SWITCH))
  666. {
  667. Mode = cmFingerprintScan;
  668. }
  669. // We have to check for /console only after the other options,
  670. // as the /console is always used when we are run by winscp.com
  671. // (ambiguous use to pass console version)
  672. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(SCRIPT_SWITCH) ||
  673. Params->FindSwitch(COMMAND_SWITCH))
  674. {
  675. Mode = cmScripting;
  676. }
  677. if (Mode != cmNone)
  678. {
  679. return Console(Mode);
  680. }
  681. TTerminalManager * TerminalManager = NULL;
  682. GlyphsModule = NULL;
  683. NonVisualDataModule = NULL;
  684. TStrings * CommandParams = new TStringList;
  685. try
  686. {
  687. TerminalManager = TTerminalManager::Instance();
  688. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  689. try
  690. {
  691. GlyphsModule = new TGlyphsModule(Application);
  692. }
  693. __finally
  694. {
  695. GUIConfiguration->ChangeResourceModule(ResourceModule);
  696. }
  697. NonVisualDataModule = new TNonVisualDataModule(Application);
  698. LogForm = NULL;
  699. // The default is 2.5s.
  700. // 20s is used by Office 2010 and Windows 10 Explorer.
  701. // Some applications use an infinite (Thunderbird, Firefox).
  702. // Overriden for some controls using THintInfo.HideTimeout
  703. Application->HintHidePause = 20000;
  704. HintWindowClass = __classid(TScreenTipHintWindow);
  705. UnicodeString IniFileName = Params->SwitchValue(INI_SWITCH);
  706. if (!IniFileName.IsEmpty())
  707. {
  708. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  709. if (!FileExists(ApiPath(IniFileNameExpanded)))
  710. {
  711. // this should be displayed rather at the very beginning.
  712. // however for simplicity (GUI-only), we do it only here.
  713. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  714. }
  715. }
  716. if (Params->FindSwitch(L"UninstallCleanup"))
  717. {
  718. MaintenanceTask();
  719. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  720. // workaround is that we create mutex in uninstaller, if it runs silent, and
  721. // ignore the UninstallCleanup, when the mutex exists.
  722. if ((OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL) &&
  723. (MessageDialog(MainInstructions(LoadStr(UNINSTALL_CLEANUP)), qtConfirmation,
  724. qaYes | qaNo, HELP_UNINSTALL_CLEANUP) == qaYes))
  725. {
  726. DoCleanupDialog(StoredSessions, Configuration);
  727. }
  728. }
  729. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  730. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  731. {
  732. MaintenanceTask();
  733. if (CheckSafe(Params))
  734. {
  735. RegisterForDefaultProtocols();
  736. Configuration->DontSave();
  737. }
  738. }
  739. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  740. {
  741. MaintenanceTask();
  742. if (CheckSafe(Params))
  743. {
  744. UnregisterForProtocols();
  745. Configuration->DontSave();
  746. }
  747. }
  748. else if (Params->FindSwitch(L"AddSearchPath"))
  749. {
  750. MaintenanceTask();
  751. if (CheckSafe(Params))
  752. {
  753. AddSearchPath(ExtractFilePath(Application->ExeName));
  754. Configuration->DontSave();
  755. }
  756. }
  757. else if (Params->FindSwitch(L"RemoveSearchPath"))
  758. {
  759. MaintenanceTask();
  760. if (CheckSafe(Params))
  761. {
  762. try
  763. {
  764. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  765. }
  766. catch(...)
  767. {
  768. // ignore errors
  769. // (RemoveSearchPath is called always on uninstallation,
  770. // even if AddSearchPath was not used, so we would get the error
  771. // always for non-priviledged user)
  772. }
  773. Configuration->DontSave();
  774. }
  775. }
  776. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  777. {
  778. MaintenanceTask();
  779. ImportSitesIfAny();
  780. }
  781. else if (Params->FindSwitch(L"Usage", SwitchValue))
  782. {
  783. MaintenanceTask();
  784. Usage(SwitchValue);
  785. }
  786. else if (Params->FindSwitch(L"Update"))
  787. {
  788. MaintenanceTask();
  789. CheckForUpdates(false);
  790. }
  791. else if (ShowUpdatesIfAvailable())
  792. {
  793. // noop
  794. }
  795. else if (Params->FindSwitch(L"Exit"))
  796. {
  797. // noop
  798. MaintenanceTask();
  799. Configuration->DontSave();
  800. }
  801. else if (Params->FindSwitch(L"MaintenanceTask"))
  802. {
  803. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  804. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  805. MaintenanceTask();
  806. Configuration->DontSave();
  807. }
  808. else
  809. {
  810. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit, pcRefresh } ParamCommand;
  811. ParamCommand = pcNone;
  812. UnicodeString AutoStartSession;
  813. UnicodeString DownloadFile;
  814. bool UseDefaults = false;
  815. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  816. if (OnlyInstance &&
  817. WinConfiguration->TemporaryDirectoryCleanup)
  818. {
  819. TemporaryDirectoryCleanup();
  820. }
  821. WinConfiguration->CheckDefaultTranslation();
  822. if (!Params->Empty)
  823. {
  824. if (Params->FindSwitch(L"Defaults") && CheckSafe(Params))
  825. {
  826. UseDefaults = true;
  827. }
  828. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  829. {
  830. ParamCommand = pcUpload;
  831. if (CommandParams->Count == 0)
  832. {
  833. throw Exception(NO_UPLOAD_LIST_ERROR);
  834. }
  835. }
  836. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  837. {
  838. if (CommandParams->Count > 0)
  839. {
  840. ParamCommand = pcUpload;
  841. }
  842. }
  843. else if (Params->FindSwitch(L"Synchronize", CommandParams, 2))
  844. {
  845. ParamCommand = pcFullSynchronize;
  846. }
  847. else if (Params->FindSwitch(L"KeepUpToDate", CommandParams, 2))
  848. {
  849. ParamCommand = pcSynchronize;
  850. }
  851. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  852. (CommandParams->Count == 1))
  853. {
  854. ParamCommand = pcEdit;
  855. }
  856. else if (Params->FindSwitch(REFRESH_SWITCH, CommandParams, 1))
  857. {
  858. ParamCommand = pcRefresh;
  859. }
  860. }
  861. if (Params->ParamCount > 0)
  862. {
  863. AutoStartSession = Params->Param[1];
  864. Params->ParamsProcessed(1, 1);
  865. if ((ParamCommand == pcNone) &&
  866. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  867. !Params->FindSwitch(NEWINSTANCE_SWICH) &&
  868. SendToAnotherInstance())
  869. {
  870. Configuration->Usage->Inc(L"SendToAnotherInstance");
  871. return 0;
  872. }
  873. UnicodeString CounterName;
  874. if (Params->FindSwitch(JUMPLIST_SWITCH))
  875. {
  876. CounterName = L"CommandLineJumpList";
  877. }
  878. else if (Params->FindSwitch(DESKTOP_SWITCH))
  879. {
  880. CounterName = L"CommandLineDesktop";
  881. }
  882. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  883. {
  884. CounterName = L"CommandLineSendToHook";
  885. }
  886. else
  887. {
  888. CounterName = L"CommandLineSession2";
  889. }
  890. Configuration->Usage->Inc(CounterName);
  891. }
  892. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  893. {
  894. AutoStartSession = StoredSessions->Sessions[0]->Name;
  895. }
  896. else
  897. {
  898. AutoStartSession = WinConfiguration->AutoStartSession;
  899. }
  900. if (ParamCommand == pcRefresh)
  901. {
  902. Refresh(AutoStartSession, (CommandParams->Count > 0 ? CommandParams->Strings[0] : UnicodeString()));
  903. return 0;
  904. }
  905. // from now flash message boxes on background
  906. SetOnForeground(false);
  907. bool NeedSession = (ParamCommand != pcNone);
  908. bool Retry;
  909. do
  910. {
  911. Retry = false;
  912. TObjectList * DataList = new TObjectList();
  913. try
  914. {
  915. GetLoginData(AutoStartSession, Params, DataList, DownloadFile, NeedSession, NULL);
  916. // GetLoginData now Aborts when session is needed and none is selected
  917. if (DebugAlwaysTrue(!NeedSession || (DataList->Count > 0)))
  918. {
  919. if (CheckSafe(Params))
  920. {
  921. UnicodeString LogFile;
  922. if (Params->FindSwitch(LOG_SWITCH, LogFile))
  923. {
  924. Configuration->TemporaryLogging(LogFile);
  925. }
  926. if (Params->FindSwitch(L"XmlLog", LogFile))
  927. {
  928. Configuration->TemporaryActionsLogging(LogFile);
  929. }
  930. }
  931. try
  932. {
  933. DebugAssert(!TerminalManager->ActiveTerminal);
  934. bool CanStart;
  935. if (DataList->Count > 0)
  936. {
  937. TerminalManager->ActiveTerminal =
  938. TerminalManager->NewTerminals(DataList);
  939. CanStart = (TerminalManager->Count > 0);
  940. }
  941. else
  942. {
  943. DebugAssert(!NeedSession);
  944. CanStart = true;
  945. }
  946. if (!CanStart)
  947. {
  948. // do not prompt with login dialog, if connection of
  949. // auto-start session (typically from command line) failed
  950. if (AutoStartSession.IsEmpty())
  951. {
  952. Retry = true;
  953. }
  954. }
  955. else
  956. {
  957. // from now on, we do not support runtime interface change
  958. CustomWinConfiguration->CanApplyInterfaceImmediately = false;
  959. TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();
  960. CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;
  961. try
  962. {
  963. // moved inside try .. __finally, because it can fail as well
  964. TerminalManager->ScpExplorer = ScpExplorer;
  965. if ((ParamCommand != pcNone) || !DownloadFile.IsEmpty())
  966. {
  967. Configuration->Usage->Inc(L"CommandLineOperation");
  968. }
  969. if (ParamCommand == pcUpload)
  970. {
  971. Upload(TerminalManager->ActiveTerminal, CommandParams, UseDefaults);
  972. }
  973. else if (ParamCommand == pcFullSynchronize)
  974. {
  975. FullSynchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  976. CommandParams, UseDefaults);
  977. }
  978. else if (ParamCommand == pcSynchronize)
  979. {
  980. Synchronize(TerminalManager->ActiveTerminal, ScpExplorer,
  981. CommandParams, UseDefaults);
  982. }
  983. else if (ParamCommand == pcEdit)
  984. {
  985. Edit(ScpExplorer, CommandParams);
  986. }
  987. else if (!DownloadFile.IsEmpty())
  988. {
  989. Download(TerminalManager->ActiveTerminal, DownloadFile,
  990. UseDefaults);
  991. }
  992. Application->Run();
  993. }
  994. __finally
  995. {
  996. TerminalManager->ScpExplorer = NULL;
  997. SAFE_DESTROY(ScpExplorer);
  998. }
  999. }
  1000. }
  1001. catch (Exception &E)
  1002. {
  1003. ShowExtendedException(&E);
  1004. }
  1005. }
  1006. }
  1007. __finally
  1008. {
  1009. delete DataList;
  1010. }
  1011. }
  1012. while (Retry);
  1013. }
  1014. }
  1015. __finally
  1016. {
  1017. delete NonVisualDataModule;
  1018. NonVisualDataModule = NULL;
  1019. ReleaseAnimationsModule();
  1020. delete GlyphsModule;
  1021. GlyphsModule = NULL;
  1022. TTerminalManager::DestroyInstance();
  1023. delete CommandParams;
  1024. }
  1025. return 0;
  1026. }