WinMain.cpp 45 KB

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