WinMain.cpp 46 KB

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