WinMain.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  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 & Explore, UnicodeString & ExploreFile)
  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 | coExplore;
  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, cooExplore))
  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. ExploreFile = UnixExtractFileName(FileName);
  182. Explore = 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. static TStartupThread * StartupThread(new TStartupThread());
  449. static TDateTime Started(Now());
  450. static TDateTime LastStartupStartupSequence(Now());
  451. static UnicodeString StartupSequence;
  452. static int LifetimeRuns = -1;
  453. //---------------------------------------------------------------------------
  454. void InterfaceStartDontMeasure()
  455. {
  456. Started = TDateTime();
  457. StartupThread->Terminate();
  458. }
  459. //---------------------------------------------------------------------------
  460. int TensOfSecondBetween(TDateTime ANow, TDateTime AThen)
  461. {
  462. return static_cast<int>(MilliSecondsBetween(ANow, AThen) / 100);
  463. }
  464. //---------------------------------------------------------------------------
  465. void AddStartupSequence(const UnicodeString & Tag)
  466. {
  467. int SequenceTensOfSecond = TensOfSecondBetween(Now(), LastStartupStartupSequence);
  468. LastStartupStartupSequence = Now();
  469. AddToList(StartupSequence, FORMAT(L"%s:%d", (Tag, SequenceTensOfSecond)), L",");
  470. }
  471. //---------------------------------------------------------------------------
  472. void InterfaceStarted()
  473. {
  474. if (Started != TDateTime())
  475. {
  476. // deliberate downcast
  477. int StartupTensOfSecond = TensOfSecondBetween(Now(), Started);
  478. int StartupSeconds = StartupTensOfSecond / 10;
  479. int StartupSecondsReal = DebugNotNull(StartupThread)->GetStartupSeconds();
  480. AppLogFmt(L"Startup time: %d.%d s (real: %d s)", (StartupTensOfSecond / 10, StartupTensOfSecond % 10, StartupSecondsReal));
  481. if (LifetimeRuns > 0)
  482. {
  483. if (LifetimeRuns == 1)
  484. {
  485. Configuration->Usage->Set(L"StartupSeconds1", StartupSeconds);
  486. }
  487. else if (LifetimeRuns == 2)
  488. {
  489. Configuration->Usage->Set(L"StartupSeconds2", StartupSeconds);
  490. }
  491. Configuration->Usage->Set(L"StartupSecondsLast", StartupSeconds);
  492. Configuration->Usage->Set(L"StartupSecondsLastReal", StartupSecondsReal);
  493. AddStartupSequence(L"I");
  494. Configuration->Usage->Set(L"StartupSequenceLast", StartupSequence);
  495. }
  496. }
  497. StartupThread->Terminate();
  498. }
  499. //---------------------------------------------------------------------------
  500. void __fastcall UpdateStaticUsage()
  501. {
  502. Configuration->Usage->Inc(L"Runs");
  503. Configuration->Usage->UpdateCurrentVersion();
  504. Configuration->Usage->Set(L"WindowsVersion", (WindowsVersionLong()));
  505. Configuration->Usage->Set(L"WindowsProductName", (WindowsProductName()));
  506. Configuration->Usage->Set(L"WindowsProductType", (static_cast<int>(GetWindowsProductType())));
  507. Configuration->Usage->Set(L"Windows64", IsWin64());
  508. Configuration->Usage->Set(L"UWP", IsUWP());
  509. Configuration->Usage->Set(L"PackageName", GetPackageName());
  510. Configuration->Usage->Set(L"DefaultLocale",
  511. // See TGUIConfiguration::GetAppliedLocaleHex()
  512. IntToHex(static_cast<int>(GetDefaultLCID()), 4));
  513. Configuration->Usage->Set(L"Locale", WinConfiguration->AppliedLocaleHex);
  514. Configuration->Usage->Set(L"EncodingMultiByteAnsi", !TEncoding::Default->IsSingleByte);
  515. Configuration->Usage->Set(L"PixelsPerInch", Screen->PixelsPerInch);
  516. int PrimaryPixelsPerInch = Screen->PrimaryMonitor->PixelsPerInch;
  517. bool PixelsPerInchMonitorsDiffer = false;
  518. for (int Index = 0; Index < Screen->MonitorCount; Index++)
  519. {
  520. if (Screen->Monitors[Index]->PixelsPerInch != PrimaryPixelsPerInch)
  521. {
  522. PixelsPerInchMonitorsDiffer = true;
  523. }
  524. }
  525. if (PrimaryPixelsPerInch != Screen->PixelsPerInch)
  526. {
  527. Configuration->Usage->Inc(L"PixelsPerInchSystemDiffered2");
  528. }
  529. Configuration->Usage->Set(L"PixelsPerInchMonitorsDiffer", PixelsPerInchMonitorsDiffer);
  530. Configuration->Usage->Set(L"WorkAreaWidth", Screen->WorkAreaWidth);
  531. Configuration->Usage->Set(L"WorkAreaHeight", Screen->WorkAreaHeight);
  532. HDC DC = GetDC(NULL);
  533. int Planes = GetDeviceCaps(DC, PLANES);
  534. int BitsPixel = GetDeviceCaps(DC, BITSPIXEL);
  535. Configuration->Usage->Set(L"ColorDepth", Planes * BitsPixel);
  536. Configuration->Usage->Set(L"MonitorCount", Screen->MonitorCount);
  537. Configuration->Usage->Set(L"NotUseThemes", !UseThemes());
  538. Configuration->Usage->Set(L"ThemeDefaultFontSize", std::unique_ptr<TFont>(new TFont())->Size);
  539. Configuration->Usage->Set(L"ThemeIconFontSize", Screen->IconFont->Size);
  540. Configuration->Usage->Set(L"SysColorWindow", ColorToRGBStr(clWindow));
  541. Configuration->Usage->Set(L"SysColorBtnFace", ColorToRGBStr(clBtnFace));
  542. Configuration->Usage->Set(L"SysColorWindowText", ColorToRGBStr(clWindowText));
  543. UnicodeString ProgramsFolder;
  544. ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);
  545. ProgramsFolder = IncludeTrailingBackslash(ExpandFileName(ProgramsFolder));
  546. UnicodeString ExeName = ExpandFileName(Application->ExeName);
  547. bool InProgramFiles = AnsiSameText(ExeName.SubString(1, ProgramsFolder.Length()), ProgramsFolder);
  548. Configuration->Usage->Set(L"InProgramFiles", InProgramFiles);
  549. Configuration->Usage->Set(L"IsInstalled", IsInstalled());
  550. Configuration->Usage->Set(L"IsInstalledMsi", IsInstalledMsi());
  551. Configuration->Usage->Set(L"Wine", IsWine());
  552. Configuration->Usage->Set(L"NetFrameworkVersion", GetNetVersionStr());
  553. Configuration->Usage->Set(L"NetCoreVersion", GetNetCoreVersionStr());
  554. Configuration->Usage->Set(L"PowerShellVersion", GetPowerShellVersionStr());
  555. Configuration->Usage->Set(L"PwshVersion", GetPowerShellCoreVersionStr());
  556. bool MsXmlInstalled;
  557. try
  558. {
  559. TMSXMLDOMDocumentFactory::CreateDOMDocument();
  560. MsXmlInstalled = true;
  561. }
  562. catch (...)
  563. {
  564. MsXmlInstalled = false;
  565. }
  566. Configuration->Usage->Set(L"MsXmlInstalled", MsXmlInstalled);
  567. UnicodeString ParentProcess = GetAncestorProcessName();
  568. // do not record the installer as a parent process
  569. if (!ParentProcess.IsEmpty() &&
  570. (!StartsText(L"winscp-", ParentProcess) || !ContainsText(ParentProcess, L"-setup")))
  571. {
  572. UnicodeString ParentProcesses = Configuration->Usage->Get(L"ParentProcesses");
  573. std::unique_ptr<TStringList> ParentProcessesList(CreateSortedStringList());
  574. ParentProcessesList->CommaText = ParentProcesses;
  575. ParentProcessesList->Add(ParentProcess.LowerCase());
  576. Configuration->Usage->Set(L"ParentProcesses", ParentProcessesList->CommaText);
  577. }
  578. WinConfiguration->UpdateStaticUsage();
  579. }
  580. //---------------------------------------------------------------------------
  581. void __fastcall UpdateFinalStaticUsage()
  582. {
  583. CoreUpdateFinalStaticUsage();
  584. }
  585. //---------------------------------------------------------------------------
  586. void __fastcall MaintenanceTask()
  587. {
  588. CoreMaintenanceTask();
  589. InterfaceStartDontMeasure();
  590. }
  591. //---------------------------------------------------------------------------
  592. typedef std::vector<HWND> THandles;
  593. typedef std::map<unsigned long, THandles> TProcesses;
  594. //---------------------------------------------------------------------------
  595. BOOL __stdcall EnumOtherInstances(HWND Handle, LPARAM AParam)
  596. {
  597. TProcesses & Processes = *reinterpret_cast<TProcesses *>(AParam);
  598. // This should be optimized to query class name already here
  599. unsigned long ProcessId;
  600. if (GetWindowThreadProcessId(Handle, &ProcessId) != 0)
  601. {
  602. Processes[ProcessId].push_back(Handle);
  603. }
  604. return TRUE;
  605. }
  606. //---------------------------------------------------------------------------
  607. static bool __fastcall SendCopyDataMessage(HWND Window, TCopyDataMessage & Message)
  608. {
  609. COPYDATASTRUCT CopyData;
  610. CopyData.cbData = sizeof(Message);
  611. CopyData.lpData = &Message;
  612. LRESULT SendResult =
  613. SendMessage(Window, WM_COPYDATA,
  614. reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));
  615. bool Result = (SendResult > 0);
  616. return Result;
  617. }
  618. //---------------------------------------------------------------------------
  619. static void __fastcall FindOtherInstances(THandles & OtherInstances)
  620. {
  621. TProcesses Processes;
  622. // FindWindow is optimization (if there's no hidden window, no point enumerating all windows to find some)
  623. if ((FindWindow(HIDDEN_WINDOW_NAME, NULL) != NULL) &&
  624. EnumWindows(EnumOtherInstances, reinterpret_cast<LPARAM>(&Processes)))
  625. {
  626. TCopyDataMessage Message;
  627. Message.Command = TCopyDataMessage::MainWindowCheck;
  628. TProcesses::const_iterator ProcessI = Processes.begin();
  629. while (ProcessI != Processes.end())
  630. {
  631. HWND HiddenWindow = NULL;
  632. THandles::const_iterator WindowI = ProcessI->second.begin();
  633. while ((HiddenWindow == NULL) && (WindowI != ProcessI->second.end()))
  634. {
  635. wchar_t ClassName[1024];
  636. if (GetClassName(*WindowI, ClassName, LENOF(ClassName)) != 0)
  637. {
  638. NULL_TERMINATE(ClassName);
  639. if (wcscmp(ClassName, HIDDEN_WINDOW_NAME) == 0)
  640. {
  641. HiddenWindow = *WindowI;
  642. }
  643. }
  644. WindowI++;
  645. }
  646. if (HiddenWindow != NULL)
  647. {
  648. WindowI = ProcessI->second.begin();
  649. while (WindowI != ProcessI->second.end())
  650. {
  651. if (*WindowI != HiddenWindow) // optimization
  652. {
  653. if (SendCopyDataMessage(*WindowI, Message))
  654. {
  655. OtherInstances.push_back(*WindowI);
  656. break;
  657. }
  658. }
  659. WindowI++;
  660. }
  661. }
  662. ProcessI++;
  663. }
  664. }
  665. }
  666. //---------------------------------------------------------------------------
  667. bool __fastcall SendToAnotherInstance()
  668. {
  669. THandles OtherInstances;
  670. FindOtherInstances(OtherInstances);
  671. bool Result = false;
  672. THandles::const_iterator I = OtherInstances.begin();
  673. while (!Result && (I != OtherInstances.end()))
  674. {
  675. HWND Handle = *I;
  676. TCopyDataMessage Message;
  677. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  678. if (SendCopyDataMessage(Handle, Message))
  679. {
  680. // Restore window, if minimized
  681. ShowWindow(Handle, SW_RESTORE);
  682. // bring it to foreground
  683. SetForegroundWindow(Handle);
  684. Message.Command = TCopyDataMessage::CommandCommandLine;
  685. wcsncpy(Message.Data.CommandLine, CmdLine, LENOF(Message.Data.CommandLine));
  686. NULL_TERMINATE(Message.Data.CommandLine);
  687. Result = SendCopyDataMessage(Handle, Message);
  688. }
  689. I++;
  690. }
  691. return Result;
  692. }
  693. //---------------------------------------------------------------------------
  694. void __fastcall Refresh(const UnicodeString & Session, const UnicodeString & Path)
  695. {
  696. THandles OtherInstances;
  697. FindOtherInstances(OtherInstances);
  698. THandles::const_iterator I = OtherInstances.begin();
  699. while (I != OtherInstances.end())
  700. {
  701. HWND Handle = *I;
  702. TCopyDataMessage Message;
  703. Message.Command = TCopyDataMessage::RefreshPanel;
  704. wcsncpy(Message.Data.Refresh.Session, Session.c_str(), LENOF(Message.Data.Refresh.Session));
  705. NULL_TERMINATE(Message.Data.Refresh.Session);
  706. wcsncpy(Message.Data.Refresh.Path, Path.c_str(), LENOF(Message.Data.Refresh.Path));
  707. NULL_TERMINATE(Message.Data.Refresh.Path);
  708. SendCopyDataMessage(Handle, Message);
  709. I++;
  710. }
  711. }
  712. //---------------------------------------------------------------------------
  713. bool __fastcall ShowUpdatesIfAvailable()
  714. {
  715. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  716. int CurrentCompoundVer = Configuration->CompoundVersion;
  717. bool NoPopup = true;
  718. bool Result =
  719. !IsUWP() &&
  720. Updates.ShowOnStartup &&
  721. Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&
  722. !Updates.Results.Disabled &&
  723. ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&
  724. !Updates.ShownResults;
  725. if (Result)
  726. {
  727. Configuration->Usage->Inc(L"UpdateStartup");
  728. Result = CheckForUpdates(true);
  729. if (Result)
  730. {
  731. Configuration->Usage->Inc(L"UpdateDownloadOpensStartup");
  732. }
  733. NoPopup = false;
  734. }
  735. else if (WinConfiguration->ShowTips)
  736. {
  737. int Days = DaysBetween(WinConfiguration->TipsShown, Now());
  738. if ((Days >= Updates.Results.TipsIntervalDays) &&
  739. (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))
  740. {
  741. UnicodeString Tip = FirstUnshownTip();
  742. if (!Tip.IsEmpty())
  743. {
  744. AutoShowNewTip();
  745. NoPopup = false;
  746. }
  747. else
  748. {
  749. Configuration->Usage->Inc(L"TipsNoUnseen");
  750. }
  751. }
  752. }
  753. if (NoPopup)
  754. {
  755. WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;
  756. }
  757. return Result;
  758. }
  759. //---------------------------------------------------------------------------
  760. int __fastcall Execute()
  761. {
  762. std::unique_ptr<TStartupThread> StartupThreadOwner(StartupThread);
  763. AddStartupSequence(L"X");
  764. DebugAssert(StoredSessions);
  765. TProgramParams * Params = TProgramParams::Instance();
  766. DebugAssert(Params);
  767. // do not flash message boxes on startup
  768. SetOnForeground(true);
  769. // let installer know, that some instance of application is running
  770. CreateMutex(NULL, False, AppName.c_str());
  771. bool OnlyInstance = (GetLastError() == 0);
  772. UpdateStaticUsage();
  773. UnicodeString KeyFile;
  774. if (Params->FindSwitch(PRIVATEKEY_SWITCH, KeyFile))
  775. {
  776. WinConfiguration->DefaultKeyFile = KeyFile;
  777. }
  778. UnicodeString ConsoleVersion;
  779. UnicodeString DotNetVersion;
  780. Params->FindSwitch(L"Console", ConsoleVersion);
  781. Params->FindSwitch(L"DotNet", DotNetVersion);
  782. if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())
  783. {
  784. RecordWrapperVersions(ConsoleVersion, DotNetVersion);
  785. }
  786. if (!DotNetVersion.IsEmpty())
  787. {
  788. Configuration->Usage->Inc(L"ConsoleDotNet");
  789. }
  790. UnicodeString SwitchValue;
  791. if (Params->FindSwitch(L"loglevel", SwitchValue))
  792. {
  793. int StarPos = SwitchValue.Pos(L"*");
  794. if (StarPos > 0)
  795. {
  796. bool LogSensitive = true;
  797. SwitchValue.Delete(StarPos, 1);
  798. if ((StarPos <= SwitchValue.Length()) &&
  799. (SwitchValue[StarPos] == L'-'))
  800. {
  801. LogSensitive = false;
  802. SwitchValue.Delete(StarPos, 1);
  803. }
  804. SwitchValue = SwitchValue.Trim();
  805. Configuration->TemporaryLogSensitive(LogSensitive);
  806. }
  807. int LogProtocol = 0; // shut up
  808. if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= -1))
  809. {
  810. Configuration->TemporaryLogProtocol(LogProtocol);
  811. }
  812. }
  813. if (Params->FindSwitch(LOGSIZE_SWITCH, SwitchValue))
  814. {
  815. int StarPos = SwitchValue.Pos(LOGSIZE_SEPARATOR);
  816. int LogMaxCount = 0;
  817. if (StarPos > 1)
  818. {
  819. if (!TryStrToInt(SwitchValue.SubString(1, StarPos - 1), LogMaxCount))
  820. {
  821. LogMaxCount = -1;
  822. }
  823. SwitchValue.Delete(1, StarPos);
  824. SwitchValue = SwitchValue.Trim();
  825. }
  826. __int64 LogMaxSize = 0; // shut up
  827. if ((LogMaxCount >= 0) &&
  828. !SwitchValue.IsEmpty() &&
  829. TryStrToSize(SwitchValue, LogMaxSize))
  830. {
  831. Configuration->TemporaryLogMaxCount(LogMaxCount);
  832. Configuration->TemporaryLogMaxSize(LogMaxSize);
  833. }
  834. }
  835. std::unique_ptr<TStrings> RawSettings(new TStringList());
  836. if (Params->FindSwitch(RAWTRANSFERSETTINGS_SWITCH, RawSettings.get()))
  837. {
  838. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings.get(), false));
  839. GUIConfiguration->LoadDefaultCopyParam(OptionsStorage.get());
  840. }
  841. TConsoleMode Mode = cmNone;
  842. if (Params->FindSwitch(L"help") || Params->FindSwitch(L"h") || Params->FindSwitch(L"?"))
  843. {
  844. Mode = cmHelp;
  845. }
  846. else if (Params->FindSwitch(L"batchsettings"))
  847. {
  848. Mode = cmBatchSettings;
  849. }
  850. else if (Params->FindSwitch(KEYGEN_SWITCH))
  851. {
  852. Mode = cmKeyGen;
  853. }
  854. else if (Params->FindSwitch(COPYID_SWITCH))
  855. {
  856. Mode = cmCopyId;
  857. }
  858. else if (Params->FindSwitch(FINGERPRINTSCAN_SWITCH))
  859. {
  860. Mode = cmFingerprintScan;
  861. }
  862. else if (Params->FindSwitch(DUMPCALLSTACK_SWITCH))
  863. {
  864. Mode = cmDumpCallstack;
  865. }
  866. else if (Params->FindSwitch(INFO_SWITCH))
  867. {
  868. Mode = cmInfo;
  869. }
  870. else if (Params->FindSwitch(COMREGISTRATION_SWITCH))
  871. {
  872. Mode = cmComRegistration;
  873. }
  874. // We have to check for /console only after the other options,
  875. // as the /console is always used when we are run by winscp.com
  876. // (ambiguous use to pass console version)
  877. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(SCRIPT_SWITCH) ||
  878. Params->FindSwitch(COMMAND_SWITCH))
  879. {
  880. Mode = cmScripting;
  881. }
  882. if (Mode != cmNone)
  883. {
  884. InterfaceStartDontMeasure();
  885. return Console(Mode);
  886. }
  887. TTerminalManager * TerminalManager = NULL;
  888. GlyphsModule = NULL;
  889. NonVisualDataModule = NULL;
  890. TStrings * CommandParams = new TStringList;
  891. AddStartupSequence(L"C");
  892. try
  893. {
  894. TerminalManager = TTerminalManager::Instance();
  895. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  896. try
  897. {
  898. GlyphsModule = new TGlyphsModule(Application);
  899. }
  900. __finally
  901. {
  902. GUIConfiguration->ChangeResourceModule(ResourceModule);
  903. }
  904. AddStartupSequence(L"G");
  905. NonVisualDataModule = new TNonVisualDataModule(Application);
  906. AddStartupSequence(L"N");
  907. // The default is 2.5s.
  908. // 20s is used by Office 2010 and Windows 10 Explorer.
  909. // Some applications use an infinite (Thunderbird, Firefox).
  910. // Overriden for some controls using THintInfo.HideTimeout
  911. Application->HintHidePause = 20000;
  912. HintWindowClass = __classid(TScreenTipHintWindow);
  913. UnicodeString IniFileName = Params->SwitchValue(INI_SWITCH);
  914. if (!IniFileName.IsEmpty() && (IniFileName != INI_NUL))
  915. {
  916. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  917. if (!FileExists(ApiPath(IniFileNameExpanded)))
  918. {
  919. // this should be displayed rather at the very beginning.
  920. // however for simplicity (GUI-only), we do it only here.
  921. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  922. }
  923. }
  924. if (Params->FindSwitch(L"UninstallCleanup"))
  925. {
  926. MaintenanceTask();
  927. Configuration->DontSave();
  928. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  929. // workaround is that we create mutex in uninstaller, if it runs silent, and
  930. // ignore the UninstallCleanup, when the mutex exists.
  931. if (OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL)
  932. {
  933. DoCleanupDialogIfAnyDataAndWanted();
  934. }
  935. }
  936. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  937. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  938. {
  939. MaintenanceTask();
  940. if (CheckSafe(Params))
  941. {
  942. RegisterForDefaultProtocols();
  943. Configuration->DontSave();
  944. }
  945. }
  946. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  947. {
  948. MaintenanceTask();
  949. if (CheckSafe(Params))
  950. {
  951. UnregisterForProtocols();
  952. Configuration->DontSave();
  953. }
  954. }
  955. else if (Params->FindSwitch(L"AddSearchPath"))
  956. {
  957. MaintenanceTask();
  958. if (CheckSafe(Params))
  959. {
  960. AddSearchPath(ExtractFilePath(Application->ExeName));
  961. Configuration->DontSave();
  962. }
  963. }
  964. else if (Params->FindSwitch(L"RemoveSearchPath"))
  965. {
  966. MaintenanceTask();
  967. if (CheckSafe(Params))
  968. {
  969. try
  970. {
  971. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  972. }
  973. catch(...)
  974. {
  975. // ignore errors
  976. // (RemoveSearchPath is called always on uninstallation,
  977. // even if AddSearchPath was not used, so we would get the error
  978. // always for non-priviledged user)
  979. }
  980. Configuration->DontSave();
  981. }
  982. }
  983. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  984. {
  985. MaintenanceTask();
  986. ImportSitesIfAny();
  987. }
  988. else if (Params->FindSwitch(L"Usage", SwitchValue))
  989. {
  990. MaintenanceTask();
  991. Usage(SwitchValue);
  992. }
  993. else if (Params->FindSwitch(L"Update"))
  994. {
  995. MaintenanceTask();
  996. CheckForUpdates(false);
  997. }
  998. else if (ShowUpdatesIfAvailable())
  999. {
  1000. // noop
  1001. }
  1002. else if (Params->FindSwitch(L"Exit"))
  1003. {
  1004. // noop
  1005. MaintenanceTask();
  1006. Configuration->DontSave();
  1007. }
  1008. else if (Params->FindSwitch(L"MaintenanceTask"))
  1009. {
  1010. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  1011. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  1012. MaintenanceTask();
  1013. Configuration->DontSave();
  1014. }
  1015. else
  1016. {
  1017. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit, pcRefresh } ParamCommand;
  1018. ParamCommand = pcNone;
  1019. UnicodeString AutoStartSession;
  1020. UnicodeString DownloadFile;
  1021. int UseDefaults = -1;
  1022. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  1023. if (OnlyInstance &&
  1024. WinConfiguration->TemporaryDirectoryCleanup)
  1025. {
  1026. TemporaryDirectoryCleanup();
  1027. }
  1028. WinConfiguration->CheckDefaultTranslation();
  1029. // Loading shell image lists here (rather than only on demand when file controls are being created)
  1030. // reduces risk of an occasional crash.
  1031. // It seems that the point is to load the lists before any call to SHGetFileInfoWithTimeout.
  1032. InitFileControls();
  1033. if (!Params->Empty)
  1034. {
  1035. UnicodeString Value;
  1036. if (Params->FindSwitch(DEFAULTS_SWITCH, Value) && CheckSafe(Params))
  1037. {
  1038. UseDefaults = StrToIntDef(Value, 0);
  1039. }
  1040. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  1041. {
  1042. ParamCommand = pcUpload;
  1043. if (CommandParams->Count == 0)
  1044. {
  1045. throw Exception(NO_UPLOAD_LIST_ERROR);
  1046. }
  1047. }
  1048. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  1049. {
  1050. if (CommandParams->Count > 0)
  1051. {
  1052. ParamCommand = pcUpload;
  1053. }
  1054. }
  1055. else if (Params->FindSwitch(SYNCHRONIZE_SWITCH, CommandParams, 4))
  1056. {
  1057. ParamCommand = pcFullSynchronize;
  1058. }
  1059. else if (Params->FindSwitch(KEEP_UP_TO_DATE_SWITCH, CommandParams, 4))
  1060. {
  1061. ParamCommand = pcSynchronize;
  1062. }
  1063. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  1064. (CommandParams->Count == 1))
  1065. {
  1066. ParamCommand = pcEdit;
  1067. }
  1068. else if (Params->FindSwitch(REFRESH_SWITCH, CommandParams, 1))
  1069. {
  1070. ParamCommand = pcRefresh;
  1071. }
  1072. }
  1073. bool NewInstance = Params->FindSwitch(NEWINSTANCE_SWICH);
  1074. if (Params->ParamCount > 0)
  1075. {
  1076. AutoStartSession = Params->ConsumeParam();
  1077. bool TrySendToAnotherInstance =
  1078. (ParamCommand == pcNone) &&
  1079. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  1080. !NewInstance &&
  1081. // With /rawconfig before session url, parsing commandline does not work correctly,
  1082. // when opening session in the other instance.
  1083. // And as it is not clear what it should do anyway, let's ban it and
  1084. // never send to the existing instance, whenever /rawconfig is used.
  1085. !Params->FindSwitch(RAW_CONFIG_SWITCH);
  1086. if (TrySendToAnotherInstance &&
  1087. !AutoStartSession.IsEmpty() &&
  1088. (AutoStartSession.Pos(L"/") > 0) && // optimization
  1089. GetFolderOrWorkspaceName(AutoStartSession).IsEmpty())
  1090. {
  1091. bool DummyDefaultsOnly = false;
  1092. UnicodeString DownloadFile2;
  1093. int Flags = GetCommandLineParseUrlFlags(Params) | pufParseOnly;
  1094. // Make copy, as ParseUrl consumes /rawsettings
  1095. TOptions Options(*Params);
  1096. std::unique_ptr<TSessionData> SessionData(
  1097. StoredSessions->ParseUrl(AutoStartSession, &Options, DummyDefaultsOnly, &DownloadFile2, NULL, NULL, Flags));
  1098. if (!DownloadFile2.IsEmpty())
  1099. {
  1100. TrySendToAnotherInstance = false;
  1101. }
  1102. }
  1103. if (TrySendToAnotherInstance &&
  1104. SendToAnotherInstance())
  1105. {
  1106. Configuration->Usage->Inc(L"SendToAnotherInstance");
  1107. return 0;
  1108. }
  1109. UnicodeString CounterName;
  1110. if (Params->FindSwitch(JUMPLIST_SWITCH))
  1111. {
  1112. CounterName = L"CommandLineJumpList";
  1113. }
  1114. else if (Params->FindSwitch(DESKTOP_SWITCH))
  1115. {
  1116. CounterName = L"CommandLineDesktop";
  1117. }
  1118. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  1119. {
  1120. CounterName = L"CommandLineSendToHook";
  1121. }
  1122. else
  1123. {
  1124. CounterName = L"CommandLineSession2";
  1125. }
  1126. Configuration->Usage->Inc(CounterName);
  1127. }
  1128. else if (NewInstance)
  1129. {
  1130. // no autostart
  1131. }
  1132. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  1133. {
  1134. AutoStartSession = StoredSessions->Sessions[0]->Name;
  1135. }
  1136. else
  1137. {
  1138. AutoStartSession = WinConfiguration->AutoStartSession;
  1139. }
  1140. if (ParamCommand == pcRefresh)
  1141. {
  1142. Refresh(AutoStartSession, (CommandParams->Count > 0 ? CommandParams->Strings[0] : UnicodeString()));
  1143. return 0;
  1144. }
  1145. // from now flash message boxes in background
  1146. SetOnForeground(false);
  1147. bool NeedSession = NewInstance || (ParamCommand != pcNone);
  1148. bool Retry;
  1149. do
  1150. {
  1151. Retry = false;
  1152. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1153. try
  1154. {
  1155. int Flags = GetCommandLineParseUrlFlags(Params);
  1156. AddStartupSequence(L"B");
  1157. GetLoginData(AutoStartSession, Params, DataList.get(), DownloadFile, NeedSession, NULL, Flags);
  1158. // GetLoginData now Aborts when session is needed and none is selected
  1159. if (DebugAlwaysTrue(!NeedSession || (DataList->Count > 0)))
  1160. {
  1161. if (CheckSafe(Params))
  1162. {
  1163. UnicodeString LogFile;
  1164. if (Params->FindSwitch(LOG_SWITCH, LogFile))
  1165. {
  1166. Configuration->TemporaryLogging(LogFile);
  1167. }
  1168. if (Params->FindSwitch(L"XmlLog", LogFile))
  1169. {
  1170. Configuration->TemporaryActionsLogging(LogFile);
  1171. }
  1172. }
  1173. try
  1174. {
  1175. DebugAssert(TerminalManager->ActiveSession == NULL);
  1176. bool CanStart;
  1177. bool Explore = false;
  1178. UnicodeString ExploreFile;
  1179. if (DataList->Count > 0)
  1180. {
  1181. TManagedTerminal * Session = TerminalManager->NewSessions(DataList.get());
  1182. if ((Params->FindSwitch(EXPLORE_SWITCH, ExploreFile) || Params->FindSwitch(EXPLORE_OLD_SWITCH, ExploreFile)) &&
  1183. (!ExploreFile.IsEmpty() || !DownloadFile.IsEmpty()))
  1184. {
  1185. if (ExploreFile.IsEmpty())
  1186. {
  1187. ExploreFile = DownloadFile;
  1188. }
  1189. DownloadFile = UnicodeString();
  1190. Explore = true;
  1191. }
  1192. if (!DownloadFile.IsEmpty())
  1193. {
  1194. Session->AutoReadDirectory = false;
  1195. DownloadFile = UnixIncludeTrailingBackslash(Session->SessionData->RemoteDirectory) + DownloadFile;
  1196. Session->SessionData->RemoteDirectory = L"";
  1197. Session->StateData->RemoteDirectory = Session->SessionData->RemoteDirectory;
  1198. }
  1199. TerminalManager->ActiveSession = Session;
  1200. CanStart = (TerminalManager->Count > 0);
  1201. }
  1202. else
  1203. {
  1204. DebugAssert(!NeedSession);
  1205. CanStart = true;
  1206. }
  1207. if (!CanStart)
  1208. {
  1209. // do not prompt with login dialog, if connection of
  1210. // auto-start session (typically from command line) failed
  1211. if (AutoStartSession.IsEmpty())
  1212. {
  1213. Retry = true;
  1214. }
  1215. }
  1216. else
  1217. {
  1218. // from now on, we do not support runtime interface change
  1219. CustomWinConfiguration->CanApplyInterfaceImmediately = false;
  1220. AddStartupSequence(L"A");
  1221. // Start loading drives on the background asap,
  1222. // to prevent unnecessary refreshes after the explorer opens
  1223. DriveInfo->NeedData();
  1224. std::unique_ptr<TCustomScpExplorerForm> ScpExplorer(CreateScpExplorer());
  1225. AddStartupSequence(L"E");
  1226. CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;
  1227. try
  1228. {
  1229. // moved inside try .. __finally, because it can fail as well
  1230. TerminalManager->ScpExplorer = ScpExplorer.get();
  1231. if ((ParamCommand != pcNone) || !DownloadFile.IsEmpty())
  1232. {
  1233. Configuration->Usage->Inc(L"CommandLineOperation");
  1234. ScpExplorer->StandaloneOperation = true;
  1235. InterfaceStartDontMeasure();
  1236. }
  1237. if (ParamCommand == pcUpload)
  1238. {
  1239. Upload(TerminalManager->ActiveSession, CommandParams, UseDefaults);
  1240. }
  1241. else if (ParamCommand == pcFullSynchronize)
  1242. {
  1243. FullSynchronize(
  1244. TerminalManager->ActiveSession, ScpExplorer.get(), CommandParams, UseDefaults);
  1245. }
  1246. else if (ParamCommand == pcSynchronize)
  1247. {
  1248. Synchronize(
  1249. TerminalManager->ActiveSession, ScpExplorer.get(), CommandParams, UseDefaults);
  1250. }
  1251. else if (ParamCommand == pcEdit)
  1252. {
  1253. Edit(ScpExplorer.get(), CommandParams);
  1254. }
  1255. else if (!DownloadFile.IsEmpty())
  1256. {
  1257. Download(
  1258. TerminalManager->ActiveSession, DownloadFile, UseDefaults, Explore, ExploreFile);
  1259. }
  1260. else
  1261. {
  1262. if (DataList->Count == 0)
  1263. {
  1264. LifetimeRuns = Configuration->Usage->Inc(L"RunsNormal");
  1265. }
  1266. }
  1267. ScpExplorer->StandaloneOperation = false;
  1268. if (Explore)
  1269. {
  1270. ScpExplorer->ExploreFile(ExploreFile);
  1271. }
  1272. AddStartupSequence(L"R");
  1273. AppLog(L"Running...");
  1274. Application->Run();
  1275. AppLog(L"Terminated.");
  1276. // to allow dialog boxes show later (like from CheckConfigurationForceSave)
  1277. SetAppTerminated(False);
  1278. }
  1279. __finally
  1280. {
  1281. TerminalManager->ScpExplorer = NULL;
  1282. }
  1283. }
  1284. }
  1285. catch (Exception &E)
  1286. {
  1287. ShowExtendedException(&E);
  1288. }
  1289. }
  1290. }
  1291. // Catch EAbort from Synchronize() and similar functions, so that CheckConfigurationForceSave is processed
  1292. catch (EAbort &)
  1293. {
  1294. Retry = false; // unlikely to be true, but just in case
  1295. }
  1296. }
  1297. while (Retry);
  1298. }
  1299. // In GUI mode only
  1300. CheckConfigurationForceSave();
  1301. UpdateFinalStaticUsage();
  1302. }
  1303. __finally
  1304. {
  1305. delete NonVisualDataModule;
  1306. NonVisualDataModule = NULL;
  1307. ReleaseImagesModules();
  1308. delete GlyphsModule;
  1309. GlyphsModule = NULL;
  1310. TTerminalManager::DestroyInstance();
  1311. delete CommandParams;
  1312. }
  1313. return 0;
  1314. }