WinMain.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <CoreMain.h>
  5. #include <TextsWin.h>
  6. #include <TextsCore.h>
  7. #include <HelpWin.h>
  8. #include "CustomScpExplorer.h"
  9. #include "TerminalManager.h"
  10. #include "NonVisual.h"
  11. #include "Glyphs.h"
  12. #include "ProgParams.h"
  13. #include "Setup.h"
  14. #include "WinConfiguration.h"
  15. #include "GUITools.h"
  16. #include "Tools.h"
  17. #include "WinApi.h"
  18. #include <DateUtils.hpp>
  19. #include <StrUtils.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, int Flags)
  25. {
  26. bool DefaultsOnly = false;
  27. UnicodeString FolderOrWorkspaceName = DecodeUrlChars(SessionName);
  28. if (StoredSessions->IsFolder(FolderOrWorkspaceName) ||
  29. StoredSessions->IsWorkspace(FolderOrWorkspaceName))
  30. {
  31. StoredSessions->GetFolderOrWorkspace(FolderOrWorkspaceName, DataList);
  32. }
  33. else
  34. {
  35. TSessionData * SessionData =
  36. StoredSessions->ParseUrl(SessionName, Options, DefaultsOnly, &DownloadFile, NULL, NULL, Flags);
  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. OpenSessionInPutty(SessionData);
  55. DataList->Clear();
  56. Abort();
  57. }
  58. }
  59. }
  60. if (DefaultsOnly && !NeedSession)
  61. {
  62. // No URL specified on command-line and no explicit command-line parameter
  63. // that requires session was specified => noop
  64. DataList->Clear();
  65. }
  66. else if ((DataList->Count == 0) ||
  67. !dynamic_cast<TSessionData *>(DataList->Items[0])->CanOpen ||
  68. DefaultsOnly)
  69. {
  70. // Note that GetFolderOrWorkspace never returns sites that !CanOpen,
  71. // so we should not get here with more than one site.
  72. // Though we should be good, if we ever do.
  73. // We get here when:
  74. // - we need session for explicit command-line operation
  75. // - after we handle "save" URL.
  76. // - the specified session does not contain enough information to open [= not even hostname nor local browser]
  77. DebugAssert(DataList->Count <= 1);
  78. if (!DoLoginDialog(DataList, LinkedForm))
  79. {
  80. Abort();
  81. }
  82. }
  83. }
  84. //---------------------------------------------------------------------------
  85. int GetCommandLineParseUrlFlags(TProgramParams * Params)
  86. {
  87. return
  88. pufAllowStoredSiteWithProtocol |
  89. FLAGMASK(!CheckSafe(Params), pufUnsafe);
  90. }
  91. //---------------------------------------------------------------------------
  92. void __fastcall Upload(TTerminal * Terminal, TStrings * FileList, int UseDefaults)
  93. {
  94. UnicodeString TargetDirectory;
  95. TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;
  96. TargetDirectory = UnixIncludeTrailingBackslash(Terminal->CurrentDirectory);
  97. std::unique_ptr<TSessionData> Data(Terminal->SessionData->Clone());
  98. Terminal->FillSessionDataForCode(Data.get());
  99. int Options = coDisableQueue;
  100. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  101. if ((UseDefaults == 0) ||
  102. DoCopyDialog(true, false, FileList, TargetDirectory, &CopyParam, Options,
  103. CopyParamAttrs, Data.get(), NULL, UseDefaults))
  104. {
  105. // Setting parameter overrides only now, otherwise the dialog would present the parametes as non-default
  106. CopyParam.OnceDoneOperation = odoDisconnect;
  107. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  108. Terminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, 0, NULL);
  109. }
  110. }
  111. //---------------------------------------------------------------------------
  112. void __fastcall Download(TTerminal * Terminal, const UnicodeString FileName, int UseDefaults)
  113. {
  114. TRemoteFile * File = NULL;
  115. try
  116. {
  117. Terminal->ExceptionOnFail = true;
  118. try
  119. {
  120. File = Terminal->ReadFile(FileName);
  121. }
  122. __finally
  123. {
  124. Terminal->ExceptionOnFail = false;
  125. }
  126. File->FullFileName = FileName;
  127. UnicodeString LocalDirectory = Terminal->SessionData->LocalDirectoryExpanded;
  128. if (LocalDirectory.IsEmpty())
  129. {
  130. LocalDirectory = GetPersonalFolder();
  131. }
  132. UnicodeString TargetDirectory = IncludeTrailingBackslash(LocalDirectory);
  133. TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;
  134. UnicodeString DisplayName = File->FileName;
  135. bool CustomDisplayName =
  136. !File->DisplayName.IsEmpty() &&
  137. (File->DisplayName != DisplayName);
  138. if (CustomDisplayName)
  139. {
  140. DisplayName = File->DisplayName;
  141. }
  142. UnicodeString FriendyFileName = UnixIncludeTrailingBackslash(UnixExtractFilePath(FileName)) + DisplayName;
  143. std::unique_ptr<TStrings> FileListFriendly(new TStringList());
  144. FileListFriendly->AddObject(FriendyFileName, File);
  145. int Options = coDisableQueue;
  146. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Download;
  147. if ((UseDefaults == 0) ||
  148. DoCopyDialog(false, false, FileListFriendly.get(), TargetDirectory, &CopyParam,
  149. Options, CopyParamAttrs, NULL, NULL, UseDefaults))
  150. {
  151. // Setting parameter overrides only now, otherwise the dialog would present the parametes as non-default
  152. if (CustomDisplayName)
  153. {
  154. // Set only now, so that it is not redundantly displayed on the copy dialog.
  155. // We should escape the * and ?'s.
  156. CopyParam.FileMask = DisplayName;
  157. }
  158. CopyParam.OnceDoneOperation = odoDisconnect;
  159. std::unique_ptr<TStrings> FileList(new TStringList());
  160. FileList->AddObject(FileName, File);
  161. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList.get());
  162. Terminal->CopyToLocal(FileList.get(), TargetDirectory, &CopyParam, 0, NULL);
  163. }
  164. UnicodeString Directory = UnixExtractFilePath(FileName);
  165. Terminal->AutoReadDirectory = true;
  166. Terminal->ChangeDirectory(Directory);
  167. }
  168. __finally
  169. {
  170. delete File;
  171. }
  172. }
  173. //---------------------------------------------------------------------------
  174. void __fastcall Edit(TCustomScpExplorerForm * ScpExplorer, TStrings * FileList)
  175. {
  176. ScpExplorer->StandaloneEdit(FileList->Strings[0]);
  177. Abort();
  178. }
  179. //---------------------------------------------------------------------------
  180. void __fastcall SynchronizeDirectories(
  181. TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams,
  182. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory)
  183. {
  184. if (CommandParams->Count >= 1)
  185. {
  186. LocalDirectory = CommandParams->Strings[0];
  187. }
  188. else if (!Terminal->SessionData->LocalDirectory.IsEmpty())
  189. {
  190. LocalDirectory = Terminal->SessionData->LocalDirectoryExpanded;
  191. }
  192. else
  193. {
  194. LocalDirectory = ScpExplorer->DefaultDownloadTargetDirectory();
  195. }
  196. if (CommandParams->Count >= 2)
  197. {
  198. RemoteDirectory = CommandParams->Strings[1];
  199. }
  200. else
  201. {
  202. RemoteDirectory = Terminal->CurrentDirectory;
  203. }
  204. }
  205. //---------------------------------------------------------------------------
  206. void __fastcall FullSynchronize(
  207. TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams, int UseDefaults)
  208. {
  209. UnicodeString LocalDirectory;
  210. UnicodeString RemoteDirectory;
  211. SynchronizeDirectories(Terminal, ScpExplorer, CommandParams, LocalDirectory, RemoteDirectory);
  212. bool SaveMode = true;
  213. // bit ugly
  214. TSynchronizeMode Mode = (TSynchronizeMode)GUIConfiguration->SynchronizeMode;
  215. int Params = GUIConfiguration->SynchronizeParams;
  216. // Undocumented syntax for "Start in New Window"
  217. if (CommandParams->Count >= 4)
  218. {
  219. Mode = (TSynchronizeMode)StrToIntDef(CommandParams->Strings[2], Mode);
  220. Params = StrToIntDef(CommandParams->Strings[3], Params);
  221. }
  222. int Result =
  223. ScpExplorer->DoFullSynchronizeDirectories(LocalDirectory, RemoteDirectory, Mode, Params, SaveMode, UseDefaults);
  224. if ((Result >= 0) && SaveMode)
  225. {
  226. GUIConfiguration->SynchronizeMode = Mode;
  227. }
  228. Abort();
  229. }
  230. //---------------------------------------------------------------------------
  231. void __fastcall Synchronize(
  232. TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams, int UseDefaults)
  233. {
  234. UnicodeString LocalDirectory;
  235. UnicodeString RemoteDirectory;
  236. SynchronizeDirectories(Terminal, ScpExplorer, CommandParams, LocalDirectory, RemoteDirectory);
  237. // Undocumented syntax for "Start in New Window"
  238. if (CommandParams->Count >= 4)
  239. {
  240. GUIConfiguration->SynchronizeParams = StrToIntDef(CommandParams->Strings[2], -1);
  241. GUIConfiguration->SynchronizeOptions = StrToIntDef(CommandParams->Strings[3], -1);
  242. Configuration->DontSave();
  243. }
  244. ScpExplorer->DoSynchronizeDirectories(LocalDirectory, RemoteDirectory, UseDefaults);
  245. Abort();
  246. }
  247. //---------------------------------------------------------------------------
  248. void __fastcall ImportSitesIfAny()
  249. {
  250. if (!WinConfiguration->AutoImportedFromPuttyOrFilezilla)
  251. {
  252. bool AnyPuttySession = GUIConfiguration->AnyPuttySessionForImport(StoredSessions);
  253. bool AnyFilezillaSession = GUIConfiguration->AnyFilezillaSessionForImport(StoredSessions);
  254. if (AnyPuttySession || AnyFilezillaSession)
  255. {
  256. UnicodeString PuttySource = LoadStrPart(IMPORT_SESSIONS2, 2);
  257. UnicodeString FilezillaSource = LoadStrPart(IMPORT_SESSIONS2, 3);
  258. UnicodeString Source;
  259. if (AnyPuttySession && AnyFilezillaSession)
  260. {
  261. Source = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 4), (PuttySource, FilezillaSource));
  262. }
  263. else if (AnyPuttySession)
  264. {
  265. Source = PuttySource;
  266. }
  267. else if (AnyFilezillaSession)
  268. {
  269. Source = FilezillaSource;
  270. }
  271. else
  272. {
  273. DebugFail();
  274. }
  275. UnicodeString Message = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 1), (Source));
  276. if (MessageDialog(Message, qtConfirmation,
  277. qaYes | qaNo, HELP_IMPORT_SESSIONS) == qaYes)
  278. {
  279. DoImportSessionsDialog(NULL);
  280. }
  281. WinConfiguration->AutoImportedFromPuttyOrFilezilla = true;
  282. }
  283. }
  284. }
  285. //---------------------------------------------------------------------------
  286. void __fastcall Usage(UnicodeString Param)
  287. {
  288. while (!Param.IsEmpty())
  289. {
  290. UnicodeString Pair = CutToChar(Param, L',', true);
  291. if (!Pair.IsEmpty())
  292. {
  293. if (Pair[Pair.Length()] == L'+')
  294. {
  295. UnicodeString Key = Pair.SubString(1, Pair.Length() - 1).Trim();
  296. Configuration->Usage->Inc(Key);
  297. }
  298. else if (Pair[Pair.Length()] == L'@')
  299. {
  300. UnicodeString Key = Pair.SubString(1, Pair.Length() - 1).Trim();
  301. UnicodeString Value;
  302. if (SameText(Key, L"InstallationParentProcess"))
  303. {
  304. Value = GetAncestorProcessName(3).LowerCase();
  305. }
  306. else
  307. {
  308. Value = L"err-unknown-key";
  309. }
  310. Configuration->Usage->Set(Key, Value);
  311. }
  312. else
  313. {
  314. UnicodeString Key = CutToChar(Pair, L':', true);
  315. UnicodeString Value = Pair.Trim();
  316. Configuration->Usage->Set(Key, Value);
  317. }
  318. }
  319. }
  320. }
  321. //---------------------------------------------------------------------------
  322. void __fastcall RecordWrapperVersions(UnicodeString ConsoleVersion, UnicodeString DotNetVersion)
  323. {
  324. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  325. if (!DotNetVersion.IsEmpty())
  326. {
  327. Updates.DotNetVersion = DotNetVersion;
  328. }
  329. if (!ConsoleVersion.IsEmpty())
  330. {
  331. Updates.ConsoleVersion = ConsoleVersion;
  332. }
  333. WinConfiguration->Updates = Updates;
  334. if ((WinConfiguration->Storage == stNul) &&
  335. WinConfiguration->TrySetSafeStorage())
  336. {
  337. try
  338. {
  339. THierarchicalStorage * Storage = WinConfiguration->CreateConfigStorage();
  340. try
  341. {
  342. Storage->AccessMode = smReadWrite;
  343. if (Storage->OpenSubKey(Configuration->ConfigurationSubKey, true) &&
  344. Storage->OpenSubKeyPath(L"Interface\\Updates", true))
  345. {
  346. if (!DotNetVersion.IsEmpty())
  347. {
  348. Storage->WriteString(L"DotNetVersion", DotNetVersion);
  349. }
  350. if (!ConsoleVersion.IsEmpty())
  351. {
  352. Storage->WriteString(L"ConsoleVersion", ConsoleVersion);
  353. }
  354. }
  355. }
  356. __finally
  357. {
  358. delete Storage;
  359. }
  360. }
  361. __finally
  362. {
  363. Configuration->SetNulStorage();
  364. }
  365. }
  366. }
  367. //---------------------------------------------------------------------------
  368. static UnicodeString ColorToRGBStr(TColor Color)
  369. {
  370. int RGB = ColorToRGB(Color);
  371. int R = GetRValue(RGB);
  372. int G = GetGValue(RGB);
  373. int B = GetBValue(RGB);
  374. UnicodeString Result = FORMAT(L"%.2x%.2x%.2x", (R, G, B));
  375. return Result;
  376. }
  377. //---------------------------------------------------------------------------
  378. class TStartupThread : public TSimpleThread
  379. {
  380. public:
  381. TStartupThread();
  382. virtual __fastcall ~TStartupThread();
  383. int GetStartupSeconds();
  384. virtual void __fastcall Terminate();
  385. protected:
  386. virtual void __fastcall Execute();
  387. int FMilliseconds;
  388. bool FStop;
  389. };
  390. //---------------------------------------------------------------------------
  391. TStartupThread::TStartupThread()
  392. {
  393. FMilliseconds = 0;
  394. FStop = false;
  395. Start();
  396. }
  397. //---------------------------------------------------------------------------
  398. __fastcall TStartupThread::~TStartupThread()
  399. {
  400. Close();
  401. }
  402. //---------------------------------------------------------------------------
  403. int TStartupThread::GetStartupSeconds()
  404. {
  405. DebugAssert(!FStop);
  406. return FMilliseconds / 1000;
  407. }
  408. //---------------------------------------------------------------------------
  409. void __fastcall TStartupThread::Terminate()
  410. {
  411. FStop = true;
  412. }
  413. //---------------------------------------------------------------------------
  414. void __fastcall TStartupThread::Execute()
  415. {
  416. while (!FStop)
  417. {
  418. const int Step = 250;
  419. Sleep(Step);
  420. FMilliseconds += Step;
  421. }
  422. }
  423. //---------------------------------------------------------------------------
  424. TStartupThread * StartupThread(new TStartupThread());
  425. TDateTime Started(Now());
  426. TDateTime LastStartupStartupSequence(Now());
  427. UnicodeString StartupSequence;
  428. int LifetimeRuns = -1;
  429. //---------------------------------------------------------------------------
  430. void InterfaceStartDontMeasure()
  431. {
  432. Started = TDateTime();
  433. StartupThread->Terminate();
  434. }
  435. //---------------------------------------------------------------------------
  436. void AddStartupSequence(const UnicodeString & Tag)
  437. {
  438. int SequenceTensOfSecond = static_cast<int>(MilliSecondsBetween(Now(), LastStartupStartupSequence) / 100);
  439. LastStartupStartupSequence = Now();
  440. AddToList(StartupSequence, FORMAT(L"%s:%d", (Tag, SequenceTensOfSecond)), L",");
  441. }
  442. //---------------------------------------------------------------------------
  443. void InterfaceStarted()
  444. {
  445. if ((Started != TDateTime()) && (LifetimeRuns > 0))
  446. {
  447. // deliberate downcast
  448. int StartupSeconds = static_cast<int>(SecondsBetween(Now(), Started));
  449. int StartupSecondsReal = DebugNotNull(StartupThread)->GetStartupSeconds();
  450. if (LifetimeRuns == 1)
  451. {
  452. Configuration->Usage->Set(L"StartupSeconds1", StartupSeconds);
  453. }
  454. else if (LifetimeRuns == 2)
  455. {
  456. Configuration->Usage->Set(L"StartupSeconds2", StartupSeconds);
  457. }
  458. Configuration->Usage->Set(L"StartupSecondsLast", StartupSeconds);
  459. Configuration->Usage->Set(L"StartupSecondsLastReal", StartupSecondsReal);
  460. AddStartupSequence(L"I");
  461. Configuration->Usage->Set(L"StartupSequenceLast", StartupSequence);
  462. }
  463. StartupThread->Terminate();
  464. }
  465. //---------------------------------------------------------------------------
  466. void __fastcall UpdateStaticUsage()
  467. {
  468. Configuration->Usage->Inc(L"Runs");
  469. Configuration->Usage->UpdateCurrentVersion();
  470. Configuration->Usage->Set(L"WindowsVersion", (WindowsVersionLong()));
  471. Configuration->Usage->Set(L"WindowsProductName", (WindowsProductName()));
  472. DWORD Type;
  473. GetWindowsProductType(Type);
  474. Configuration->Usage->Set(L"WindowsProductType", (static_cast<int>(Type)));
  475. Configuration->Usage->Set(L"Windows64", IsWin64());
  476. Configuration->Usage->Set(L"UWP", IsUWP());
  477. Configuration->Usage->Set(L"PackageName", GetPackageName());
  478. Configuration->Usage->Set(L"DefaultLocale",
  479. // See TGUIConfiguration::GetAppliedLocaleHex()
  480. IntToHex(static_cast<int>(GetDefaultLCID()), 4));
  481. Configuration->Usage->Set(L"Locale", WinConfiguration->AppliedLocaleHex);
  482. Configuration->Usage->Set(L"EncodingMultiByteAnsi", !TEncoding::Default->IsSingleByte);
  483. Configuration->Usage->Set(L"PixelsPerInch", Screen->PixelsPerInch);
  484. bool PixelsPerInchSystemDiffers = false;
  485. bool PixelsPerInchMonitorsDiffer = false;
  486. bool PixelsPerInchAxesDiffer = false;
  487. HINSTANCE ShCoreLibrary = LoadLibrary(L"shcore.dll");
  488. if (ShCoreLibrary != NULL)
  489. {
  490. GetDpiForMonitorProc GetDpiForMonitor =
  491. (GetDpiForMonitorProc)GetProcAddress(ShCoreLibrary, "GetDpiForMonitor");
  492. if (GetDpiForMonitor != NULL)
  493. {
  494. unsigned int PrimaryDpiX;
  495. unsigned int PrimaryDpiY;
  496. for (int Index = 0; Index < Screen->MonitorCount; Index++)
  497. {
  498. unsigned int DpiX;
  499. unsigned int DpiY;
  500. GetDpiForMonitor(Screen->Monitors[Index]->Handle, MDT_Default, &DpiX, &DpiY);
  501. if (DpiX != DpiY)
  502. {
  503. PixelsPerInchAxesDiffer = true;
  504. }
  505. if (Index == 0)
  506. {
  507. PrimaryDpiX = DpiX;
  508. PrimaryDpiY = DpiY;
  509. // PixelsPerInch is GetDeviceCaps(DC, LOGPIXELSY)
  510. if (DpiY != (unsigned int)Screen->PixelsPerInch)
  511. {
  512. PixelsPerInchSystemDiffers = true;
  513. }
  514. }
  515. else
  516. {
  517. if ((DpiX != PrimaryDpiX) ||
  518. (DpiY != PrimaryDpiY))
  519. {
  520. PixelsPerInchMonitorsDiffer = true;
  521. }
  522. }
  523. }
  524. }
  525. }
  526. if (PixelsPerInchSystemDiffers)
  527. {
  528. Configuration->Usage->Inc(L"PixelsPerInchSystemDiffered");
  529. }
  530. Configuration->Usage->Set(L"PixelsPerInchMonitorsDiffer", PixelsPerInchMonitorsDiffer);
  531. Configuration->Usage->Set(L"PixelsPerInchAxesDiffer", PixelsPerInchAxesDiffer);
  532. Configuration->Usage->Set(L"WorkAreaWidth", Screen->WorkAreaWidth);
  533. Configuration->Usage->Set(L"WorkAreaHeight", Screen->WorkAreaHeight);
  534. HDC DC = GetDC(NULL);
  535. int Planes = GetDeviceCaps(DC, PLANES);
  536. int BitsPixel = GetDeviceCaps(DC, BITSPIXEL);
  537. Configuration->Usage->Set(L"ColorDepth", Planes * BitsPixel);
  538. Configuration->Usage->Set(L"MonitorCount", Screen->MonitorCount);
  539. Configuration->Usage->Set(L"NotUseThemes", !UseThemes());
  540. Configuration->Usage->Set(L"ThemeDefaultFontSize", Application->DefaultFont->Size);
  541. Configuration->Usage->Set(L"ThemeIconFontSize", Screen->IconFont->Size);
  542. Configuration->Usage->Set(L"SysColorWindow", ColorToRGBStr(clWindow));
  543. Configuration->Usage->Set(L"SysColorBtnFace", ColorToRGBStr(clBtnFace));
  544. Configuration->Usage->Set(L"SysColorWindowText", ColorToRGBStr(clWindowText));
  545. UnicodeString ProgramsFolder;
  546. ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);
  547. ProgramsFolder = IncludeTrailingBackslash(ExpandFileName(ProgramsFolder));
  548. UnicodeString ExeName = ExpandFileName(Application->ExeName);
  549. bool InProgramFiles = AnsiSameText(ExeName.SubString(1, ProgramsFolder.Length()), ProgramsFolder);
  550. Configuration->Usage->Set(L"InProgramFiles", InProgramFiles);
  551. Configuration->Usage->Set(L"IsInstalled", IsInstalled());
  552. Configuration->Usage->Set(L"IsInstalledMsi", IsInstalledMsi());
  553. Configuration->Usage->Set(L"Wine", IsWine());
  554. Configuration->Usage->Set(L"NetFrameworkVersion", GetNetVersionStr());
  555. Configuration->Usage->Set(L"NetCoreVersion", GetNetCoreVersionStr());
  556. Configuration->Usage->Set(L"PowerShellVersion", GetPowerShellVersionStr());
  557. Configuration->Usage->Set(L"PwshVersion", GetPowerShellCoreVersionStr());
  558. UnicodeString ParentProcess = GetAncestorProcessName();
  559. // do not record the installer as a parent process
  560. if (!ParentProcess.IsEmpty() &&
  561. (!StartsText(L"winscp-", ParentProcess) || !ContainsText(ParentProcess, L"-setup")))
  562. {
  563. UnicodeString ParentProcesses = Configuration->Usage->Get(L"ParentProcesses");
  564. std::unique_ptr<TStringList> ParentProcessesList(CreateSortedStringList());
  565. ParentProcessesList->CommaText = ParentProcesses;
  566. ParentProcessesList->Add(ParentProcess.LowerCase());
  567. Configuration->Usage->Set(L"ParentProcesses", ParentProcessesList->CommaText);
  568. }
  569. WinConfiguration->UpdateStaticUsage();
  570. }
  571. //---------------------------------------------------------------------------
  572. void __fastcall UpdateFinalStaticUsage()
  573. {
  574. CoreUpdateFinalStaticUsage();
  575. }
  576. //---------------------------------------------------------------------------
  577. void __fastcall MaintenanceTask()
  578. {
  579. CoreMaintenanceTask();
  580. InterfaceStartDontMeasure();
  581. }
  582. //---------------------------------------------------------------------------
  583. typedef std::vector<HWND> THandles;
  584. typedef std::map<unsigned long, THandles> TProcesses;
  585. //---------------------------------------------------------------------------
  586. BOOL __stdcall EnumOtherInstances(HWND Handle, LPARAM AParam)
  587. {
  588. TProcesses & Processes = *reinterpret_cast<TProcesses *>(AParam);
  589. // This should be optimized to query class name already here
  590. unsigned long ProcessId;
  591. if (GetWindowThreadProcessId(Handle, &ProcessId) != 0)
  592. {
  593. Processes[ProcessId].push_back(Handle);
  594. }
  595. return TRUE;
  596. }
  597. //---------------------------------------------------------------------------
  598. static bool __fastcall SendCopyDataMessage(HWND Window, TCopyDataMessage & Message)
  599. {
  600. COPYDATASTRUCT CopyData;
  601. CopyData.cbData = sizeof(Message);
  602. CopyData.lpData = &Message;
  603. LRESULT SendResult =
  604. SendMessage(Window, WM_COPYDATA,
  605. reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));
  606. bool Result = (SendResult > 0);
  607. return Result;
  608. }
  609. //---------------------------------------------------------------------------
  610. static void __fastcall FindOtherInstances(THandles & OtherInstances)
  611. {
  612. TProcesses Processes;
  613. // FindWindow is optimization (if there's no hidden window, no point enumerating all windows to find some)
  614. if ((FindWindow(HIDDEN_WINDOW_NAME, NULL) != NULL) &&
  615. EnumWindows(EnumOtherInstances, reinterpret_cast<LPARAM>(&Processes)))
  616. {
  617. TCopyDataMessage Message;
  618. Message.Command = TCopyDataMessage::MainWindowCheck;
  619. TProcesses::const_iterator ProcessI = Processes.begin();
  620. while (ProcessI != Processes.end())
  621. {
  622. HWND HiddenWindow = NULL;
  623. THandles::const_iterator WindowI = ProcessI->second.begin();
  624. while ((HiddenWindow == NULL) && (WindowI != ProcessI->second.end()))
  625. {
  626. wchar_t ClassName[1024];
  627. if (GetClassName(*WindowI, ClassName, LENOF(ClassName)) != 0)
  628. {
  629. NULL_TERMINATE(ClassName);
  630. if (wcscmp(ClassName, HIDDEN_WINDOW_NAME) == 0)
  631. {
  632. HiddenWindow = *WindowI;
  633. }
  634. }
  635. WindowI++;
  636. }
  637. if (HiddenWindow != NULL)
  638. {
  639. WindowI = ProcessI->second.begin();
  640. while (WindowI != ProcessI->second.end())
  641. {
  642. if (*WindowI != HiddenWindow) // optimization
  643. {
  644. if (SendCopyDataMessage(*WindowI, Message))
  645. {
  646. OtherInstances.push_back(*WindowI);
  647. break;
  648. }
  649. }
  650. WindowI++;
  651. }
  652. }
  653. ProcessI++;
  654. }
  655. }
  656. }
  657. //---------------------------------------------------------------------------
  658. bool __fastcall SendToAnotherInstance()
  659. {
  660. THandles OtherInstances;
  661. FindOtherInstances(OtherInstances);
  662. bool Result = false;
  663. THandles::const_iterator I = OtherInstances.begin();
  664. while (!Result && (I != OtherInstances.end()))
  665. {
  666. HWND Handle = *I;
  667. TCopyDataMessage Message;
  668. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  669. if (SendCopyDataMessage(Handle, Message))
  670. {
  671. // Restore window, if minimized
  672. ShowWindow(Handle, SW_RESTORE);
  673. // bring it to foreground
  674. SetForegroundWindow(Handle);
  675. Message.Command = TCopyDataMessage::CommandCommandLine;
  676. wcsncpy(Message.CommandLine, CmdLine, LENOF(Message.CommandLine));
  677. NULL_TERMINATE(Message.CommandLine);
  678. Result = SendCopyDataMessage(Handle, Message);
  679. }
  680. I++;
  681. }
  682. return Result;
  683. }
  684. //---------------------------------------------------------------------------
  685. void __fastcall Refresh(const UnicodeString & Session, const UnicodeString & Path)
  686. {
  687. THandles OtherInstances;
  688. FindOtherInstances(OtherInstances);
  689. THandles::const_iterator I = OtherInstances.begin();
  690. while (I != OtherInstances.end())
  691. {
  692. HWND Handle = *I;
  693. TCopyDataMessage Message;
  694. Message.Command = TCopyDataMessage::RefreshPanel;
  695. wcsncpy(Message.Refresh.Session, Session.c_str(), LENOF(Message.Refresh.Session));
  696. NULL_TERMINATE(Message.Refresh.Session);
  697. wcsncpy(Message.Refresh.Path, Path.c_str(), LENOF(Message.Refresh.Path));
  698. NULL_TERMINATE(Message.Refresh.Path);
  699. SendCopyDataMessage(Handle, Message);
  700. I++;
  701. }
  702. }
  703. //---------------------------------------------------------------------------
  704. bool __fastcall ShowUpdatesIfAvailable()
  705. {
  706. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  707. int CurrentCompoundVer = Configuration->CompoundVersion;
  708. bool NoPopup = true;
  709. bool Result =
  710. !IsUWP() &&
  711. Updates.ShowOnStartup &&
  712. Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&
  713. !Updates.Results.Disabled &&
  714. ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&
  715. !Updates.ShownResults;
  716. if (Result)
  717. {
  718. Configuration->Usage->Inc(L"UpdateStartup");
  719. Result = CheckForUpdates(true);
  720. if (Result)
  721. {
  722. Configuration->Usage->Inc(L"UpdateDownloadOpensStartup");
  723. }
  724. NoPopup = false;
  725. }
  726. else if (WinConfiguration->ShowTips)
  727. {
  728. int Days = DaysBetween(WinConfiguration->TipsShown, Now());
  729. if ((Days >= Updates.Results.TipsIntervalDays) &&
  730. (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))
  731. {
  732. UnicodeString Tip = FirstUnshownTip();
  733. if (!Tip.IsEmpty())
  734. {
  735. AutoShowNewTip();
  736. NoPopup = false;
  737. }
  738. else
  739. {
  740. Configuration->Usage->Inc(L"TipsNoUnseen");
  741. }
  742. }
  743. }
  744. if (NoPopup)
  745. {
  746. WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;
  747. }
  748. return Result;
  749. }
  750. //---------------------------------------------------------------------------
  751. int __fastcall Execute()
  752. {
  753. AddStartupSequence(L"E");
  754. DebugAssert(StoredSessions);
  755. TProgramParams * Params = TProgramParams::Instance();
  756. DebugAssert(Params);
  757. // do not flash message boxes on startup
  758. SetOnForeground(true);
  759. // let installer know, that some instance of application is running
  760. CreateMutex(NULL, False, AppName.c_str());
  761. bool OnlyInstance = (GetLastError() == 0);
  762. UpdateStaticUsage();
  763. UnicodeString KeyFile;
  764. if (Params->FindSwitch(PRIVATEKEY_SWITCH, KeyFile))
  765. {
  766. WinConfiguration->DefaultKeyFile = KeyFile;
  767. }
  768. UnicodeString ConsoleVersion;
  769. UnicodeString DotNetVersion;
  770. Params->FindSwitch(L"Console", ConsoleVersion);
  771. Params->FindSwitch(L"DotNet", DotNetVersion);
  772. if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())
  773. {
  774. RecordWrapperVersions(ConsoleVersion, DotNetVersion);
  775. }
  776. if (!DotNetVersion.IsEmpty())
  777. {
  778. Configuration->Usage->Inc(L"ConsoleDotNet");
  779. }
  780. UnicodeString SwitchValue;
  781. if (Params->FindSwitch(L"loglevel", SwitchValue))
  782. {
  783. int StarPos = SwitchValue.Pos(L"*");
  784. if (StarPos > 0)
  785. {
  786. bool LogSensitive = true;
  787. SwitchValue.Delete(StarPos, 1);
  788. if ((StarPos <= SwitchValue.Length()) &&
  789. (SwitchValue[StarPos] == L'-'))
  790. {
  791. LogSensitive = false;
  792. SwitchValue.Delete(StarPos, 1);
  793. }
  794. SwitchValue = SwitchValue.Trim();
  795. Configuration->TemporaryLogSensitive(LogSensitive);
  796. }
  797. int LogProtocol;
  798. if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= -1))
  799. {
  800. Configuration->TemporaryLogProtocol(LogProtocol);
  801. }
  802. }
  803. if (Params->FindSwitch(LOGSIZE_SWITCH, SwitchValue))
  804. {
  805. int StarPos = SwitchValue.Pos(LOGSIZE_SEPARATOR);
  806. int LogMaxCount = 0;
  807. if (StarPos > 1)
  808. {
  809. if (!TryStrToInt(SwitchValue.SubString(1, StarPos - 1), LogMaxCount))
  810. {
  811. LogMaxCount = -1;
  812. }
  813. SwitchValue.Delete(1, StarPos);
  814. SwitchValue = SwitchValue.Trim();
  815. }
  816. __int64 LogMaxSize;
  817. if ((LogMaxCount >= 0) &&
  818. !SwitchValue.IsEmpty() &&
  819. TryStrToSize(SwitchValue, LogMaxSize))
  820. {
  821. Configuration->TemporaryLogMaxCount(LogMaxCount);
  822. Configuration->TemporaryLogMaxSize(LogMaxSize);
  823. }
  824. }
  825. std::unique_ptr<TStrings> RawSettings(new TStringList());
  826. if (Params->FindSwitch(RAWTRANSFERSETTINGS_SWITCH, RawSettings.get()))
  827. {
  828. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings.get(), false));
  829. GUIConfiguration->LoadDefaultCopyParam(OptionsStorage.get());
  830. }
  831. TConsoleMode Mode = cmNone;
  832. if (Params->FindSwitch(L"help") || Params->FindSwitch(L"h") || Params->FindSwitch(L"?"))
  833. {
  834. Mode = cmHelp;
  835. }
  836. else if (Params->FindSwitch(L"batchsettings"))
  837. {
  838. Mode = cmBatchSettings;
  839. }
  840. else if (Params->FindSwitch(KEYGEN_SWITCH))
  841. {
  842. Mode = cmKeyGen;
  843. }
  844. else if (Params->FindSwitch(FINGERPRINTSCAN_SWITCH))
  845. {
  846. Mode = cmFingerprintScan;
  847. }
  848. else if (Params->FindSwitch(DUMPCALLSTACK_SWITCH))
  849. {
  850. Mode = cmDumpCallstack;
  851. }
  852. else if (Params->FindSwitch(INFO_SWITCH))
  853. {
  854. Mode = cmInfo;
  855. }
  856. else if (Params->FindSwitch(COMREGISTRATION_SWITCH))
  857. {
  858. Mode = cmComRegistration;
  859. }
  860. // We have to check for /console only after the other options,
  861. // as the /console is always used when we are run by winscp.com
  862. // (ambiguous use to pass console version)
  863. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(SCRIPT_SWITCH) ||
  864. Params->FindSwitch(COMMAND_SWITCH))
  865. {
  866. Mode = cmScripting;
  867. }
  868. if (Mode != cmNone)
  869. {
  870. InterfaceStartDontMeasure();
  871. return Console(Mode);
  872. }
  873. TTerminalManager * TerminalManager = NULL;
  874. GlyphsModule = NULL;
  875. NonVisualDataModule = NULL;
  876. TStrings * CommandParams = new TStringList;
  877. AddStartupSequence(L"C");
  878. try
  879. {
  880. TerminalManager = TTerminalManager::Instance();
  881. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  882. try
  883. {
  884. GlyphsModule = new TGlyphsModule(Application);
  885. }
  886. __finally
  887. {
  888. GUIConfiguration->ChangeResourceModule(ResourceModule);
  889. }
  890. AddStartupSequence(L"G");
  891. NonVisualDataModule = new TNonVisualDataModule(Application);
  892. AddStartupSequence(L"N");
  893. // The default is 2.5s.
  894. // 20s is used by Office 2010 and Windows 10 Explorer.
  895. // Some applications use an infinite (Thunderbird, Firefox).
  896. // Overriden for some controls using THintInfo.HideTimeout
  897. Application->HintHidePause = 20000;
  898. HintWindowClass = __classid(TScreenTipHintWindow);
  899. UnicodeString IniFileName = Params->SwitchValue(INI_SWITCH);
  900. if (!IniFileName.IsEmpty() && (IniFileName != INI_NUL))
  901. {
  902. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  903. if (!FileExists(ApiPath(IniFileNameExpanded)))
  904. {
  905. // this should be displayed rather at the very beginning.
  906. // however for simplicity (GUI-only), we do it only here.
  907. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  908. }
  909. }
  910. if (Params->FindSwitch(L"UninstallCleanup"))
  911. {
  912. MaintenanceTask();
  913. Configuration->DontSave();
  914. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  915. // workaround is that we create mutex in uninstaller, if it runs silent, and
  916. // ignore the UninstallCleanup, when the mutex exists.
  917. if (OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL)
  918. {
  919. DoCleanupDialogIfAnyDataAndWanted();
  920. }
  921. }
  922. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  923. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  924. {
  925. MaintenanceTask();
  926. if (CheckSafe(Params))
  927. {
  928. RegisterForDefaultProtocols();
  929. Configuration->DontSave();
  930. }
  931. }
  932. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  933. {
  934. MaintenanceTask();
  935. if (CheckSafe(Params))
  936. {
  937. UnregisterForProtocols();
  938. Configuration->DontSave();
  939. }
  940. }
  941. else if (Params->FindSwitch(L"AddSearchPath"))
  942. {
  943. MaintenanceTask();
  944. if (CheckSafe(Params))
  945. {
  946. AddSearchPath(ExtractFilePath(Application->ExeName));
  947. Configuration->DontSave();
  948. }
  949. }
  950. else if (Params->FindSwitch(L"RemoveSearchPath"))
  951. {
  952. MaintenanceTask();
  953. if (CheckSafe(Params))
  954. {
  955. try
  956. {
  957. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  958. }
  959. catch(...)
  960. {
  961. // ignore errors
  962. // (RemoveSearchPath is called always on uninstallation,
  963. // even if AddSearchPath was not used, so we would get the error
  964. // always for non-priviledged user)
  965. }
  966. Configuration->DontSave();
  967. }
  968. }
  969. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  970. {
  971. MaintenanceTask();
  972. ImportSitesIfAny();
  973. }
  974. else if (Params->FindSwitch(L"Usage", SwitchValue))
  975. {
  976. MaintenanceTask();
  977. Usage(SwitchValue);
  978. }
  979. else if (Params->FindSwitch(L"Update"))
  980. {
  981. MaintenanceTask();
  982. CheckForUpdates(false);
  983. }
  984. else if (ShowUpdatesIfAvailable())
  985. {
  986. // noop
  987. }
  988. else if (Params->FindSwitch(L"Exit"))
  989. {
  990. // noop
  991. MaintenanceTask();
  992. Configuration->DontSave();
  993. }
  994. else if (Params->FindSwitch(L"MaintenanceTask"))
  995. {
  996. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  997. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  998. MaintenanceTask();
  999. Configuration->DontSave();
  1000. }
  1001. else
  1002. {
  1003. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit, pcRefresh } ParamCommand;
  1004. ParamCommand = pcNone;
  1005. UnicodeString AutoStartSession;
  1006. UnicodeString DownloadFile;
  1007. int UseDefaults = -1;
  1008. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  1009. if (OnlyInstance &&
  1010. WinConfiguration->TemporaryDirectoryCleanup)
  1011. {
  1012. TemporaryDirectoryCleanup();
  1013. }
  1014. WinConfiguration->CheckDefaultTranslation();
  1015. // Loading shell image lists here (rather than only on demand when file controls are being created)
  1016. // reduces risk of an occasional crash.
  1017. // It seems that the point is to load the lists before any call to SHGetFileInfoWithTimeout.
  1018. InitFileControls();
  1019. if (!Params->Empty)
  1020. {
  1021. UnicodeString Value;
  1022. if (Params->FindSwitch(DEFAULTS_SWITCH, Value) && CheckSafe(Params))
  1023. {
  1024. UseDefaults = StrToIntDef(Value, 0);
  1025. }
  1026. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  1027. {
  1028. ParamCommand = pcUpload;
  1029. if (CommandParams->Count == 0)
  1030. {
  1031. throw Exception(NO_UPLOAD_LIST_ERROR);
  1032. }
  1033. }
  1034. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  1035. {
  1036. if (CommandParams->Count > 0)
  1037. {
  1038. ParamCommand = pcUpload;
  1039. }
  1040. }
  1041. else if (Params->FindSwitch(SYNCHRONIZE_SWITCH, CommandParams, 4))
  1042. {
  1043. ParamCommand = pcFullSynchronize;
  1044. }
  1045. else if (Params->FindSwitch(KEEP_UP_TO_DATE_SWITCH, CommandParams, 4))
  1046. {
  1047. ParamCommand = pcSynchronize;
  1048. }
  1049. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  1050. (CommandParams->Count == 1))
  1051. {
  1052. ParamCommand = pcEdit;
  1053. }
  1054. else if (Params->FindSwitch(REFRESH_SWITCH, CommandParams, 1))
  1055. {
  1056. ParamCommand = pcRefresh;
  1057. }
  1058. }
  1059. bool NewInstance = Params->FindSwitch(NEWINSTANCE_SWICH);
  1060. if (Params->ParamCount > 0)
  1061. {
  1062. AutoStartSession = Params->ConsumeParam();
  1063. if ((ParamCommand == pcNone) &&
  1064. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  1065. !NewInstance &&
  1066. SendToAnotherInstance())
  1067. {
  1068. Configuration->Usage->Inc(L"SendToAnotherInstance");
  1069. return 0;
  1070. }
  1071. UnicodeString CounterName;
  1072. if (Params->FindSwitch(JUMPLIST_SWITCH))
  1073. {
  1074. CounterName = L"CommandLineJumpList";
  1075. }
  1076. else if (Params->FindSwitch(DESKTOP_SWITCH))
  1077. {
  1078. CounterName = L"CommandLineDesktop";
  1079. }
  1080. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  1081. {
  1082. CounterName = L"CommandLineSendToHook";
  1083. }
  1084. else
  1085. {
  1086. CounterName = L"CommandLineSession2";
  1087. }
  1088. Configuration->Usage->Inc(CounterName);
  1089. }
  1090. else if (NewInstance)
  1091. {
  1092. // no autostart
  1093. }
  1094. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  1095. {
  1096. AutoStartSession = StoredSessions->Sessions[0]->Name;
  1097. }
  1098. else
  1099. {
  1100. AutoStartSession = WinConfiguration->AutoStartSession;
  1101. }
  1102. if (ParamCommand == pcRefresh)
  1103. {
  1104. Refresh(AutoStartSession, (CommandParams->Count > 0 ? CommandParams->Strings[0] : UnicodeString()));
  1105. return 0;
  1106. }
  1107. // from now flash message boxes on background
  1108. SetOnForeground(false);
  1109. bool NeedSession = NewInstance || (ParamCommand != pcNone);
  1110. bool Retry;
  1111. do
  1112. {
  1113. Retry = false;
  1114. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1115. try
  1116. {
  1117. int Flags = GetCommandLineParseUrlFlags(Params);
  1118. AddStartupSequence(L"B");
  1119. GetLoginData(AutoStartSession, Params, DataList.get(), DownloadFile, NeedSession, NULL, Flags);
  1120. // GetLoginData now Aborts when session is needed and none is selected
  1121. if (DebugAlwaysTrue(!NeedSession || (DataList->Count > 0)))
  1122. {
  1123. if (CheckSafe(Params))
  1124. {
  1125. UnicodeString LogFile;
  1126. if (Params->FindSwitch(LOG_SWITCH, LogFile))
  1127. {
  1128. Configuration->TemporaryLogging(LogFile);
  1129. }
  1130. if (Params->FindSwitch(L"XmlLog", LogFile))
  1131. {
  1132. Configuration->TemporaryActionsLogging(LogFile);
  1133. }
  1134. }
  1135. try
  1136. {
  1137. DebugAssert(TerminalManager->ActiveSession == NULL);
  1138. bool CanStart;
  1139. bool Browse = false;
  1140. if (DataList->Count > 0)
  1141. {
  1142. TManagedTerminal * Session = TerminalManager->NewSessions(DataList.get());
  1143. UnicodeString BrowseFile;
  1144. if (Params->FindSwitch(BROWSE_SWITCH, BrowseFile) &&
  1145. (!BrowseFile.IsEmpty() || !DownloadFile.IsEmpty()))
  1146. {
  1147. if (BrowseFile.IsEmpty())
  1148. {
  1149. BrowseFile = DownloadFile;
  1150. }
  1151. DebugAssert(Session->RemoteExplorerState == NULL);
  1152. Session->RemoteExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);
  1153. DebugAssert(Session->LocalExplorerState == NULL);
  1154. Session->LocalExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);
  1155. DownloadFile = UnicodeString();
  1156. Browse = true;
  1157. }
  1158. if (!DownloadFile.IsEmpty())
  1159. {
  1160. Session->AutoReadDirectory = false;
  1161. DownloadFile = UnixIncludeTrailingBackslash(Session->SessionData->RemoteDirectory) + DownloadFile;
  1162. Session->SessionData->RemoteDirectory = L"";
  1163. Session->StateData->RemoteDirectory = Session->SessionData->RemoteDirectory;
  1164. }
  1165. TerminalManager->ActiveSession = Session;
  1166. CanStart = (TerminalManager->Count > 0);
  1167. }
  1168. else
  1169. {
  1170. DebugAssert(!NeedSession);
  1171. CanStart = true;
  1172. }
  1173. if (!CanStart)
  1174. {
  1175. // do not prompt with login dialog, if connection of
  1176. // auto-start session (typically from command line) failed
  1177. if (AutoStartSession.IsEmpty())
  1178. {
  1179. Retry = true;
  1180. }
  1181. }
  1182. else
  1183. {
  1184. // from now on, we do not support runtime interface change
  1185. CustomWinConfiguration->CanApplyInterfaceImmediately = false;
  1186. AddStartupSequence(L"A");
  1187. TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();
  1188. AddStartupSequence(L"E");
  1189. CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;
  1190. try
  1191. {
  1192. // moved inside try .. __finally, because it can fail as well
  1193. TerminalManager->ScpExplorer = ScpExplorer;
  1194. if ((ParamCommand != pcNone) || !DownloadFile.IsEmpty())
  1195. {
  1196. Configuration->Usage->Inc(L"CommandLineOperation");
  1197. ScpExplorer->StandaloneOperation = true;
  1198. InterfaceStartDontMeasure();
  1199. }
  1200. if (ParamCommand == pcUpload)
  1201. {
  1202. Upload(TerminalManager->ActiveSession, CommandParams, UseDefaults);
  1203. }
  1204. else if (ParamCommand == pcFullSynchronize)
  1205. {
  1206. FullSynchronize(TerminalManager->ActiveSession, ScpExplorer,
  1207. CommandParams, UseDefaults);
  1208. }
  1209. else if (ParamCommand == pcSynchronize)
  1210. {
  1211. Synchronize(TerminalManager->ActiveSession, ScpExplorer,
  1212. CommandParams, UseDefaults);
  1213. }
  1214. else if (ParamCommand == pcEdit)
  1215. {
  1216. Edit(ScpExplorer, CommandParams);
  1217. }
  1218. else if (!DownloadFile.IsEmpty())
  1219. {
  1220. Download(TerminalManager->ActiveSession, DownloadFile,
  1221. UseDefaults);
  1222. }
  1223. else
  1224. {
  1225. if (DataList->Count == 0)
  1226. {
  1227. LifetimeRuns = Configuration->Usage->Inc(L"RunsNormal");
  1228. }
  1229. }
  1230. ScpExplorer->StandaloneOperation = false;
  1231. if (Browse)
  1232. {
  1233. ScpExplorer->BrowseFile();
  1234. }
  1235. AddStartupSequence(L"R");
  1236. Application->Run();
  1237. // to allow dialog boxes show later (like from CheckConfigurationForceSave)
  1238. SetAppTerminated(False);
  1239. }
  1240. __finally
  1241. {
  1242. TerminalManager->ScpExplorer = NULL;
  1243. SAFE_DESTROY(ScpExplorer);
  1244. }
  1245. }
  1246. }
  1247. catch (Exception &E)
  1248. {
  1249. ShowExtendedException(&E);
  1250. }
  1251. }
  1252. }
  1253. // Catch EAbort from Synchronize() and similar functions, so that CheckConfigurationForceSave is processed
  1254. catch (EAbort & E)
  1255. {
  1256. Retry = false; // unlikely to be true, but just in case
  1257. }
  1258. }
  1259. while (Retry);
  1260. }
  1261. // In GUI mode only
  1262. CheckConfigurationForceSave();
  1263. UpdateFinalStaticUsage();
  1264. }
  1265. __finally
  1266. {
  1267. delete NonVisualDataModule;
  1268. NonVisualDataModule = NULL;
  1269. ReleaseImagesModules();
  1270. delete GlyphsModule;
  1271. GlyphsModule = NULL;
  1272. TTerminalManager::DestroyInstance();
  1273. delete CommandParams;
  1274. delete StartupThread;
  1275. }
  1276. return 0;
  1277. }