WinMain.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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"IsInstalledMsi", IsInstalledMsi());
  553. Configuration->Usage->Set(L"Wine", IsWine());
  554. Configuration->Usage->Set(L"NetFrameworkVersion", GetNetVersionStr());
  555. Configuration->Usage->Set(L"NetCoreVersion", GetNetCoreVersionStr());
  556. Configuration->Usage->Set(L"PowerShellVersion", GetPowerShellVersionStr());
  557. Configuration->Usage->Set(L"PwshVersion", GetPowerShellCoreVersionStr());
  558. UnicodeString ParentProcess = GetAncestorProcessName();
  559. // do not record the installer as a parent process
  560. if (!ParentProcess.IsEmpty() &&
  561. (!StartsText(L"winscp-", ParentProcess) || !ContainsText(ParentProcess, L"-setup")))
  562. {
  563. UnicodeString ParentProcesses = Configuration->Usage->Get(L"ParentProcesses");
  564. std::unique_ptr<TStringList> ParentProcessesList(CreateSortedStringList());
  565. ParentProcessesList->CommaText = ParentProcesses;
  566. ParentProcessesList->Add(ParentProcess.LowerCase());
  567. Configuration->Usage->Set(L"ParentProcesses", ParentProcessesList->CommaText);
  568. }
  569. WinConfiguration->UpdateStaticUsage();
  570. }
  571. //---------------------------------------------------------------------------
  572. void __fastcall UpdateFinalStaticUsage()
  573. {
  574. CoreUpdateFinalStaticUsage();
  575. }
  576. //---------------------------------------------------------------------------
  577. void __fastcall MaintenanceTask()
  578. {
  579. CoreMaintenanceTask();
  580. InterfaceStartDontMeasure();
  581. }
  582. //---------------------------------------------------------------------------
  583. typedef std::vector<HWND> THandles;
  584. typedef std::map<unsigned long, THandles> TProcesses;
  585. //---------------------------------------------------------------------------
  586. BOOL __stdcall EnumOtherInstances(HWND Handle, LPARAM AParam)
  587. {
  588. TProcesses & Processes = *reinterpret_cast<TProcesses *>(AParam);
  589. unsigned long ProcessId;
  590. if (GetWindowThreadProcessId(Handle, &ProcessId) != 0)
  591. {
  592. Processes[ProcessId].push_back(Handle);
  593. }
  594. return TRUE;
  595. }
  596. //---------------------------------------------------------------------------
  597. static bool __fastcall SendCopyDataMessage(HWND Window, TCopyDataMessage & Message)
  598. {
  599. COPYDATASTRUCT CopyData;
  600. CopyData.cbData = sizeof(Message);
  601. CopyData.lpData = &Message;
  602. LRESULT SendResult =
  603. SendMessage(Window, WM_COPYDATA,
  604. reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));
  605. bool Result = (SendResult > 0);
  606. return Result;
  607. }
  608. //---------------------------------------------------------------------------
  609. static void __fastcall FindOtherInstances(THandles & OtherInstances)
  610. {
  611. TProcesses Processes;
  612. // FindWindow is optimization (if there's no hidden window, no point enumerating all windows to find some)
  613. if ((FindWindow(HIDDEN_WINDOW_NAME, NULL) != NULL) &&
  614. EnumWindows(EnumOtherInstances, reinterpret_cast<LPARAM>(&Processes)))
  615. {
  616. TCopyDataMessage Message;
  617. Message.Command = TCopyDataMessage::MainWindowCheck;
  618. TProcesses::const_iterator ProcessI = Processes.begin();
  619. while (ProcessI != Processes.end())
  620. {
  621. HWND HiddenWindow = NULL;
  622. THandles::const_iterator WindowI = ProcessI->second.begin();
  623. while ((HiddenWindow == NULL) && (WindowI != ProcessI->second.end()))
  624. {
  625. wchar_t ClassName[1024];
  626. if (GetClassName(*WindowI, ClassName, LENOF(ClassName)) != 0)
  627. {
  628. NULL_TERMINATE(ClassName);
  629. if (wcscmp(ClassName, HIDDEN_WINDOW_NAME) == 0)
  630. {
  631. HiddenWindow = *WindowI;
  632. }
  633. }
  634. WindowI++;
  635. }
  636. if (HiddenWindow != NULL)
  637. {
  638. WindowI = ProcessI->second.begin();
  639. while (WindowI != ProcessI->second.end())
  640. {
  641. if (*WindowI != HiddenWindow) // optimization
  642. {
  643. if (SendCopyDataMessage(*WindowI, Message))
  644. {
  645. OtherInstances.push_back(*WindowI);
  646. break;
  647. }
  648. }
  649. WindowI++;
  650. }
  651. }
  652. ProcessI++;
  653. }
  654. }
  655. }
  656. //---------------------------------------------------------------------------
  657. bool __fastcall SendToAnotherInstance()
  658. {
  659. THandles OtherInstances;
  660. FindOtherInstances(OtherInstances);
  661. bool Result = false;
  662. THandles::const_iterator I = OtherInstances.begin();
  663. while (!Result && (I != OtherInstances.end()))
  664. {
  665. HWND Handle = *I;
  666. TCopyDataMessage Message;
  667. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  668. if (SendCopyDataMessage(Handle, Message))
  669. {
  670. // Restore window, if minimized
  671. ShowWindow(Handle, SW_RESTORE);
  672. // bring it to foreground
  673. SetForegroundWindow(Handle);
  674. Message.Command = TCopyDataMessage::CommandCommandLine;
  675. wcsncpy(Message.CommandLine, CmdLine, LENOF(Message.CommandLine));
  676. NULL_TERMINATE(Message.CommandLine);
  677. Result = SendCopyDataMessage(Handle, Message);
  678. }
  679. I++;
  680. }
  681. return Result;
  682. }
  683. //---------------------------------------------------------------------------
  684. void __fastcall Refresh(const UnicodeString & Session, const UnicodeString & Path)
  685. {
  686. THandles OtherInstances;
  687. FindOtherInstances(OtherInstances);
  688. THandles::const_iterator I = OtherInstances.begin();
  689. while (I != OtherInstances.end())
  690. {
  691. HWND Handle = *I;
  692. TCopyDataMessage Message;
  693. Message.Command = TCopyDataMessage::RefreshPanel;
  694. wcsncpy(Message.Refresh.Session, Session.c_str(), LENOF(Message.Refresh.Session));
  695. NULL_TERMINATE(Message.Refresh.Session);
  696. wcsncpy(Message.Refresh.Path, Path.c_str(), LENOF(Message.Refresh.Path));
  697. NULL_TERMINATE(Message.Refresh.Path);
  698. SendCopyDataMessage(Handle, Message);
  699. I++;
  700. }
  701. }
  702. //---------------------------------------------------------------------------
  703. bool __fastcall ShowUpdatesIfAvailable()
  704. {
  705. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  706. int CurrentCompoundVer = Configuration->CompoundVersion;
  707. bool NoPopup = true;
  708. bool Result =
  709. !IsUWP() &&
  710. Updates.ShowOnStartup &&
  711. Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&
  712. !Updates.Results.Disabled &&
  713. ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&
  714. !Updates.ShownResults;
  715. if (Result)
  716. {
  717. Configuration->Usage->Inc(L"UpdateStartup");
  718. Result = CheckForUpdates(true);
  719. if (Result)
  720. {
  721. Configuration->Usage->Inc(L"UpdateDownloadOpensStartup");
  722. }
  723. NoPopup = false;
  724. }
  725. else if (WinConfiguration->ShowTips)
  726. {
  727. int Days = DaysBetween(WinConfiguration->TipsShown, Now());
  728. if ((Days >= Updates.Results.TipsIntervalDays) &&
  729. (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))
  730. {
  731. UnicodeString Tip = FirstUnshownTip();
  732. if (!Tip.IsEmpty())
  733. {
  734. AutoShowNewTip();
  735. NoPopup = false;
  736. }
  737. else
  738. {
  739. Configuration->Usage->Inc(L"TipsNoUnseen");
  740. }
  741. }
  742. }
  743. if (NoPopup)
  744. {
  745. WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;
  746. }
  747. return Result;
  748. }
  749. //---------------------------------------------------------------------------
  750. int __fastcall Execute()
  751. {
  752. AddStartupSequence(L"E");
  753. DebugAssert(StoredSessions);
  754. TProgramParams * Params = TProgramParams::Instance();
  755. DebugAssert(Params);
  756. // do not flash message boxes on startup
  757. SetOnForeground(true);
  758. // let installer know, that some instance of application is running
  759. CreateMutex(NULL, False, AppName.c_str());
  760. bool OnlyInstance = (GetLastError() == 0);
  761. UpdateStaticUsage();
  762. UnicodeString KeyFile;
  763. if (Params->FindSwitch(PRIVATEKEY_SWITCH, KeyFile))
  764. {
  765. WinConfiguration->DefaultKeyFile = KeyFile;
  766. }
  767. UnicodeString ConsoleVersion;
  768. UnicodeString DotNetVersion;
  769. Params->FindSwitch(L"Console", ConsoleVersion);
  770. Params->FindSwitch(L"DotNet", DotNetVersion);
  771. if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())
  772. {
  773. RecordWrapperVersions(ConsoleVersion, DotNetVersion);
  774. }
  775. if (!DotNetVersion.IsEmpty())
  776. {
  777. Configuration->Usage->Inc(L"ConsoleDotNet");
  778. }
  779. UnicodeString SwitchValue;
  780. if (Params->FindSwitch(L"loglevel", SwitchValue))
  781. {
  782. int StarPos = SwitchValue.Pos(L"*");
  783. if (StarPos > 0)
  784. {
  785. bool LogSensitive = true;
  786. SwitchValue.Delete(StarPos, 1);
  787. if ((StarPos <= SwitchValue.Length()) &&
  788. (SwitchValue[StarPos] == L'-'))
  789. {
  790. LogSensitive = false;
  791. SwitchValue.Delete(StarPos, 1);
  792. }
  793. SwitchValue = SwitchValue.Trim();
  794. Configuration->TemporaryLogSensitive(LogSensitive);
  795. }
  796. int LogProtocol;
  797. if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= -1))
  798. {
  799. Configuration->TemporaryLogProtocol(LogProtocol);
  800. }
  801. }
  802. if (Params->FindSwitch(LOGSIZE_SWITCH, SwitchValue))
  803. {
  804. int StarPos = SwitchValue.Pos(LOGSIZE_SEPARATOR);
  805. int LogMaxCount = 0;
  806. if (StarPos > 1)
  807. {
  808. if (!TryStrToInt(SwitchValue.SubString(1, StarPos - 1), LogMaxCount))
  809. {
  810. LogMaxCount = -1;
  811. }
  812. SwitchValue.Delete(1, StarPos);
  813. SwitchValue = SwitchValue.Trim();
  814. }
  815. __int64 LogMaxSize;
  816. if ((LogMaxCount >= 0) &&
  817. !SwitchValue.IsEmpty() &&
  818. TryStrToSize(SwitchValue, LogMaxSize))
  819. {
  820. Configuration->TemporaryLogMaxCount(LogMaxCount);
  821. Configuration->TemporaryLogMaxSize(LogMaxSize);
  822. }
  823. }
  824. std::unique_ptr<TStrings> RawSettings(new TStringList());
  825. if (Params->FindSwitch(RAWTRANSFERSETTINGS_SWITCH, RawSettings.get()))
  826. {
  827. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings.get(), false));
  828. GUIConfiguration->LoadDefaultCopyParam(OptionsStorage.get());
  829. }
  830. TConsoleMode Mode = cmNone;
  831. if (Params->FindSwitch(L"help") || Params->FindSwitch(L"h") || Params->FindSwitch(L"?"))
  832. {
  833. Mode = cmHelp;
  834. }
  835. else if (Params->FindSwitch(L"batchsettings"))
  836. {
  837. Mode = cmBatchSettings;
  838. }
  839. else if (Params->FindSwitch(KEYGEN_SWITCH))
  840. {
  841. Mode = cmKeyGen;
  842. }
  843. else if (Params->FindSwitch(FINGERPRINTSCAN_SWITCH))
  844. {
  845. Mode = cmFingerprintScan;
  846. }
  847. else if (Params->FindSwitch(DUMPCALLSTACK_SWITCH))
  848. {
  849. Mode = cmDumpCallstack;
  850. }
  851. else if (Params->FindSwitch(INFO_SWITCH))
  852. {
  853. Mode = cmInfo;
  854. }
  855. else if (Params->FindSwitch(COMREGISTRATION_SWITCH))
  856. {
  857. Mode = cmComRegistration;
  858. }
  859. // We have to check for /console only after the other options,
  860. // as the /console is always used when we are run by winscp.com
  861. // (ambiguous use to pass console version)
  862. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(SCRIPT_SWITCH) ||
  863. Params->FindSwitch(COMMAND_SWITCH))
  864. {
  865. Mode = cmScripting;
  866. }
  867. if (Mode != cmNone)
  868. {
  869. InterfaceStartDontMeasure();
  870. return Console(Mode);
  871. }
  872. TTerminalManager * TerminalManager = NULL;
  873. GlyphsModule = NULL;
  874. NonVisualDataModule = NULL;
  875. TStrings * CommandParams = new TStringList;
  876. AddStartupSequence(L"C");
  877. try
  878. {
  879. TerminalManager = TTerminalManager::Instance();
  880. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  881. try
  882. {
  883. GlyphsModule = new TGlyphsModule(Application);
  884. }
  885. __finally
  886. {
  887. GUIConfiguration->ChangeResourceModule(ResourceModule);
  888. }
  889. AddStartupSequence(L"G");
  890. NonVisualDataModule = new TNonVisualDataModule(Application);
  891. AddStartupSequence(L"N");
  892. // The default is 2.5s.
  893. // 20s is used by Office 2010 and Windows 10 Explorer.
  894. // Some applications use an infinite (Thunderbird, Firefox).
  895. // Overriden for some controls using THintInfo.HideTimeout
  896. Application->HintHidePause = 20000;
  897. HintWindowClass = __classid(TScreenTipHintWindow);
  898. UnicodeString IniFileName = Params->SwitchValue(INI_SWITCH);
  899. if (!IniFileName.IsEmpty() && (IniFileName != INI_NUL))
  900. {
  901. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  902. if (!FileExists(ApiPath(IniFileNameExpanded)))
  903. {
  904. // this should be displayed rather at the very beginning.
  905. // however for simplicity (GUI-only), we do it only here.
  906. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  907. }
  908. }
  909. if (Params->FindSwitch(L"UninstallCleanup"))
  910. {
  911. MaintenanceTask();
  912. Configuration->DontSave();
  913. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  914. // workaround is that we create mutex in uninstaller, if it runs silent, and
  915. // ignore the UninstallCleanup, when the mutex exists.
  916. if (OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL)
  917. {
  918. DoCleanupDialogIfAnyDataAndWanted();
  919. }
  920. }
  921. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  922. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  923. {
  924. MaintenanceTask();
  925. if (CheckSafe(Params))
  926. {
  927. RegisterForDefaultProtocols();
  928. Configuration->DontSave();
  929. }
  930. }
  931. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  932. {
  933. MaintenanceTask();
  934. if (CheckSafe(Params))
  935. {
  936. UnregisterForProtocols();
  937. Configuration->DontSave();
  938. }
  939. }
  940. else if (Params->FindSwitch(L"AddSearchPath"))
  941. {
  942. MaintenanceTask();
  943. if (CheckSafe(Params))
  944. {
  945. AddSearchPath(ExtractFilePath(Application->ExeName));
  946. Configuration->DontSave();
  947. }
  948. }
  949. else if (Params->FindSwitch(L"RemoveSearchPath"))
  950. {
  951. MaintenanceTask();
  952. if (CheckSafe(Params))
  953. {
  954. try
  955. {
  956. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  957. }
  958. catch(...)
  959. {
  960. // ignore errors
  961. // (RemoveSearchPath is called always on uninstallation,
  962. // even if AddSearchPath was not used, so we would get the error
  963. // always for non-priviledged user)
  964. }
  965. Configuration->DontSave();
  966. }
  967. }
  968. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  969. {
  970. MaintenanceTask();
  971. ImportSitesIfAny();
  972. }
  973. else if (Params->FindSwitch(L"Usage", SwitchValue))
  974. {
  975. MaintenanceTask();
  976. Usage(SwitchValue);
  977. }
  978. else if (Params->FindSwitch(L"Update"))
  979. {
  980. MaintenanceTask();
  981. CheckForUpdates(false);
  982. }
  983. else if (ShowUpdatesIfAvailable())
  984. {
  985. // noop
  986. }
  987. else if (Params->FindSwitch(L"Exit"))
  988. {
  989. // noop
  990. MaintenanceTask();
  991. Configuration->DontSave();
  992. }
  993. else if (Params->FindSwitch(L"MaintenanceTask"))
  994. {
  995. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  996. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  997. MaintenanceTask();
  998. Configuration->DontSave();
  999. }
  1000. else
  1001. {
  1002. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit, pcRefresh } ParamCommand;
  1003. ParamCommand = pcNone;
  1004. UnicodeString AutoStartSession;
  1005. UnicodeString DownloadFile;
  1006. int UseDefaults = -1;
  1007. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  1008. if (OnlyInstance &&
  1009. WinConfiguration->TemporaryDirectoryCleanup)
  1010. {
  1011. TemporaryDirectoryCleanup();
  1012. }
  1013. WinConfiguration->CheckDefaultTranslation();
  1014. // Loading shell image lists here (rather than only on demand when file controls are being created)
  1015. // reduces risk of an occasional crash.
  1016. // It seems that the point is to load the lists before any call to SHGetFileInfoWithTimeout.
  1017. InitFileControls();
  1018. if (!Params->Empty)
  1019. {
  1020. UnicodeString Value;
  1021. if (Params->FindSwitch(DEFAULTS_SWITCH, Value) && CheckSafe(Params))
  1022. {
  1023. UseDefaults = StrToIntDef(Value, 0);
  1024. }
  1025. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  1026. {
  1027. ParamCommand = pcUpload;
  1028. if (CommandParams->Count == 0)
  1029. {
  1030. throw Exception(NO_UPLOAD_LIST_ERROR);
  1031. }
  1032. }
  1033. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  1034. {
  1035. if (CommandParams->Count > 0)
  1036. {
  1037. ParamCommand = pcUpload;
  1038. }
  1039. }
  1040. else if (Params->FindSwitch(SYNCHRONIZE_SWITCH, CommandParams, 4))
  1041. {
  1042. ParamCommand = pcFullSynchronize;
  1043. }
  1044. else if (Params->FindSwitch(KEEP_UP_TO_DATE_SWITCH, CommandParams, 4))
  1045. {
  1046. ParamCommand = pcSynchronize;
  1047. }
  1048. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  1049. (CommandParams->Count == 1))
  1050. {
  1051. ParamCommand = pcEdit;
  1052. }
  1053. else if (Params->FindSwitch(REFRESH_SWITCH, CommandParams, 1))
  1054. {
  1055. ParamCommand = pcRefresh;
  1056. }
  1057. }
  1058. bool NewInstance = Params->FindSwitch(NEWINSTANCE_SWICH);
  1059. if (Params->ParamCount > 0)
  1060. {
  1061. AutoStartSession = Params->Param[1];
  1062. Params->ParamsProcessed(1, 1);
  1063. if ((ParamCommand == pcNone) &&
  1064. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  1065. !NewInstance &&
  1066. SendToAnotherInstance())
  1067. {
  1068. Configuration->Usage->Inc(L"SendToAnotherInstance");
  1069. return 0;
  1070. }
  1071. UnicodeString CounterName;
  1072. if (Params->FindSwitch(JUMPLIST_SWITCH))
  1073. {
  1074. CounterName = L"CommandLineJumpList";
  1075. }
  1076. else if (Params->FindSwitch(DESKTOP_SWITCH))
  1077. {
  1078. CounterName = L"CommandLineDesktop";
  1079. }
  1080. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  1081. {
  1082. CounterName = L"CommandLineSendToHook";
  1083. }
  1084. else
  1085. {
  1086. CounterName = L"CommandLineSession2";
  1087. }
  1088. Configuration->Usage->Inc(CounterName);
  1089. }
  1090. else if (NewInstance)
  1091. {
  1092. // no autostart
  1093. }
  1094. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  1095. {
  1096. AutoStartSession = StoredSessions->Sessions[0]->Name;
  1097. }
  1098. else
  1099. {
  1100. AutoStartSession = WinConfiguration->AutoStartSession;
  1101. }
  1102. if (ParamCommand == pcRefresh)
  1103. {
  1104. Refresh(AutoStartSession, (CommandParams->Count > 0 ? CommandParams->Strings[0] : UnicodeString()));
  1105. return 0;
  1106. }
  1107. // from now flash message boxes on background
  1108. SetOnForeground(false);
  1109. bool NeedSession = NewInstance || (ParamCommand != pcNone);
  1110. bool Retry;
  1111. do
  1112. {
  1113. Retry = false;
  1114. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1115. try
  1116. {
  1117. int Flags = GetCommandLineParseUrlFlags(Params);
  1118. AddStartupSequence(L"B");
  1119. GetLoginData(AutoStartSession, Params, DataList.get(), DownloadFile, NeedSession, NULL, Flags);
  1120. // GetLoginData now Aborts when session is needed and none is selected
  1121. if (DebugAlwaysTrue(!NeedSession || (DataList->Count > 0)))
  1122. {
  1123. if (CheckSafe(Params))
  1124. {
  1125. UnicodeString LogFile;
  1126. if (Params->FindSwitch(LOG_SWITCH, LogFile))
  1127. {
  1128. Configuration->TemporaryLogging(LogFile);
  1129. }
  1130. if (Params->FindSwitch(L"XmlLog", LogFile))
  1131. {
  1132. Configuration->TemporaryActionsLogging(LogFile);
  1133. }
  1134. }
  1135. try
  1136. {
  1137. DebugAssert(TerminalManager->ActiveSession == NULL);
  1138. bool CanStart;
  1139. bool Browse = false;
  1140. if (DataList->Count > 0)
  1141. {
  1142. TManagedTerminal * Session = TerminalManager->NewSessions(DataList.get());
  1143. UnicodeString BrowseFile;
  1144. if (Params->FindSwitch(BROWSE_SWITCH, BrowseFile) &&
  1145. (!BrowseFile.IsEmpty() || !DownloadFile.IsEmpty()))
  1146. {
  1147. if (BrowseFile.IsEmpty())
  1148. {
  1149. BrowseFile = DownloadFile;
  1150. }
  1151. DebugAssert(Session->RemoteExplorerState == NULL);
  1152. Session->RemoteExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);
  1153. DebugAssert(Session->LocalExplorerState == NULL);
  1154. Session->LocalExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);
  1155. DownloadFile = UnicodeString();
  1156. Browse = true;
  1157. }
  1158. if (!DownloadFile.IsEmpty())
  1159. {
  1160. Session->AutoReadDirectory = false;
  1161. DownloadFile = UnixIncludeTrailingBackslash(Session->SessionData->RemoteDirectory) + DownloadFile;
  1162. Session->SessionData->RemoteDirectory = L"";
  1163. Session->StateData->RemoteDirectory = Session->SessionData->RemoteDirectory;
  1164. }
  1165. TerminalManager->ActiveSession = Session;
  1166. CanStart = (TerminalManager->Count > 0);
  1167. }
  1168. else
  1169. {
  1170. DebugAssert(!NeedSession);
  1171. CanStart = true;
  1172. }
  1173. if (!CanStart)
  1174. {
  1175. // do not prompt with login dialog, if connection of
  1176. // auto-start session (typically from command line) failed
  1177. if (AutoStartSession.IsEmpty())
  1178. {
  1179. Retry = true;
  1180. }
  1181. }
  1182. else
  1183. {
  1184. // from now on, we do not support runtime interface change
  1185. CustomWinConfiguration->CanApplyInterfaceImmediately = false;
  1186. AddStartupSequence(L"A");
  1187. TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();
  1188. AddStartupSequence(L"E");
  1189. CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;
  1190. try
  1191. {
  1192. // moved inside try .. __finally, because it can fail as well
  1193. TerminalManager->ScpExplorer = ScpExplorer;
  1194. if ((ParamCommand != pcNone) || !DownloadFile.IsEmpty())
  1195. {
  1196. Configuration->Usage->Inc(L"CommandLineOperation");
  1197. ScpExplorer->StandaloneOperation = true;
  1198. InterfaceStartDontMeasure();
  1199. }
  1200. if (ParamCommand == pcUpload)
  1201. {
  1202. Upload(TerminalManager->ActiveSession, CommandParams, UseDefaults);
  1203. }
  1204. else if (ParamCommand == pcFullSynchronize)
  1205. {
  1206. FullSynchronize(TerminalManager->ActiveSession, ScpExplorer,
  1207. CommandParams, UseDefaults);
  1208. }
  1209. else if (ParamCommand == pcSynchronize)
  1210. {
  1211. Synchronize(TerminalManager->ActiveSession, ScpExplorer,
  1212. CommandParams, UseDefaults);
  1213. }
  1214. else if (ParamCommand == pcEdit)
  1215. {
  1216. Edit(ScpExplorer, CommandParams);
  1217. }
  1218. else if (!DownloadFile.IsEmpty())
  1219. {
  1220. Download(TerminalManager->ActiveSession, DownloadFile,
  1221. UseDefaults);
  1222. }
  1223. else
  1224. {
  1225. if (DataList->Count == 0)
  1226. {
  1227. LifetimeRuns = Configuration->Usage->Inc(L"RunsNormal");
  1228. }
  1229. }
  1230. ScpExplorer->StandaloneOperation = false;
  1231. if (Browse)
  1232. {
  1233. ScpExplorer->BrowseFile();
  1234. }
  1235. AddStartupSequence(L"R");
  1236. Application->Run();
  1237. // to allow dialog boxes show later (like from CheckConfigurationForceSave)
  1238. SetAppTerminated(False);
  1239. }
  1240. __finally
  1241. {
  1242. TerminalManager->ScpExplorer = NULL;
  1243. SAFE_DESTROY(ScpExplorer);
  1244. }
  1245. }
  1246. }
  1247. catch (Exception &E)
  1248. {
  1249. ShowExtendedException(&E);
  1250. }
  1251. }
  1252. }
  1253. // Catch EAbort from Synchronize() and similar functions, so that CheckConfigurationForceSave is processed
  1254. catch (EAbort & E)
  1255. {
  1256. Retry = false; // unlikely to be true, but just in case
  1257. }
  1258. }
  1259. while (Retry);
  1260. }
  1261. // In GUI mode only
  1262. CheckConfigurationForceSave();
  1263. UpdateFinalStaticUsage();
  1264. }
  1265. __finally
  1266. {
  1267. delete NonVisualDataModule;
  1268. NonVisualDataModule = NULL;
  1269. ReleaseImagesModules();
  1270. delete GlyphsModule;
  1271. GlyphsModule = NULL;
  1272. TTerminalManager::DestroyInstance();
  1273. delete CommandParams;
  1274. delete StartupThread;
  1275. }
  1276. return 0;
  1277. }