WinMain.cpp 46 KB

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