WinMain.cpp 47 KB

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