WinMain.cpp 46 KB

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