WinMain.cpp 46 KB

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