1
0

WinMain.cpp 46 KB

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