WinMain.cpp 46 KB

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